Python:从子类访问父属性

2024-09-23 22:28:23 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我有以下代码作为一个问答题:

class Big_Cat:
    def __init__(self):
        self.x = "dangerous"

class Cat(Big_Cat):
    def __init__(self):
        self.y = "quiet"

new_cat = Cat()
print(new_cat.x, new_cat.y)

因为cat类是从BigCat类继承的,所以它还应该可以访问变量x。那么为什么它会在打印屏幕行上抛出错误呢。new_cat如何从父级访问变量x


Tags: 代码selfnew屏幕initdefclasscat
3条回答

从超类继承后,必须调用父类的__init__(构造函数)。可以使用^{}获取对父类的引用

以下是一个例子:

class Big_Cat:
    def __init__(self):
        self.x = "dangerous"

class Cat(Big_Cat):
    def __init__(self):
        super().__init__()
        self.y = "quiet"

new_cat = Cat()
print(new_cat.x, new_cat.y)

输出

dangerous quiet

可以使用super调用父类__init__

In [1829]: class Big_Cat:
      ...:     def __init__(self):
      ...:         self.x = "dangerous"
      ...: 
      ...: class Cat(Big_Cat):
      ...:     def __init__(self):
      ...:         super(Cat, self).__init__()
      ...:         self.y = "quiet"
      ...: 
      ...: new_cat = Cat()

In [1830]: new_cat.x
Out[1830]: 'dangerous'

您需要在子类的构造函数中调用父类的构造函数,以便子类访问父类的方法和属性。您可以使用super()方法来完成此操作

class Big_Cat:
    def __init__(self):
        self.x = "dangerous"

class Cat(Big_Cat):
    def __init__(self):
        super().__init__()
        self.y = "quiet"
        
new_cat = Cat()
print(new_cat.x, new_cat.y)

相关问题 更多 >