问题描述
当我尝试从父级的类函数继承属性时,出现AttributeError。这是否意味着我不能直接从父函数继承它?这是输出:
这是代码本身:
这是代码:
class One:
def ready(self):
self.name = 'John'
class Two(One):
def __init__(self):
print(self.name)
two = Two()
解决方法
在类One的实例中,仅在调用self.ready()
时设置属性名称。当您尝试在Two.__init__
中打印时,尚未添加它,因此会引发错误。因此,您需要使用类似以下内容的
class One:
def ready(self):
self.name = 'John'
class Two(One):
def __init__(self):
self.ready()
print(self.name)
two = Two()
,
由于没有在类2中定义任何self.name,因此出现属性错误。即使两个都是从One继承的,类实例还是不同的。您可以尝试
class Two(One):
def __init__(self):
One.ready(self)
print(self.name)
如果您想获得更好的主意,请尝试在python中搜索什么是self,继承和构造函数。