Python:从子类访问父属性

Cra*_*der 1 python python-3.x

在 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)
Run Code Online (Sandbox Code Playgroud)

由于 cat 类继承自该类BigCat,因此它也应该有权访问变量x。那么为什么它会在打印屏幕行上抛出错误。还有什么方法可以从父级new_cat访问变量?x

Dev*_*Cl9 5

从超类继承后,必须调用父类的__init__(构造函数)。您可以使用 来获取对父类的引用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)
Run Code Online (Sandbox Code Playgroud)

输出

dangerous quiet
Run Code Online (Sandbox Code Playgroud)