Python AttributeError: Class Inheritance From a Parent Function

Python AttributeError: Class Inheritance From a Parent Function

当我试图从父级的 class 函数继承一个属性时,我收到一个 AttributeError。这是否意味着我不能直接从父函数继承它?这是输出:

AttributeError: 'Two' 对象没有属性 'name'

这是代码本身:

这是代码:

class One:
def ready(self):
    self.name = 'John'

class Two(One):
def __init__(self):
    print(self.name)

two = Two()

您收到属性错误,因为您没有在 class 中定义任何 self.name 二。尽管两个继承自一个 class 实例是不同的。你可以试试

   class Two(One):
     def __init__(self):
         One.ready(self)
         print(self.name)

如果您想获得更好的想法,请尝试在 python 中搜索什么是自我、继承和构造函数。

在 class 的一个实例中,属性名称仅在调用 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()