在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:
从超类继承后,必须调用父类的} 获取对父类的引用
__init__
(构造函数)。可以使用^{以下是一个例子:
输出:
可以使用
super
调用父类__init__
您需要在子类的构造函数中调用父类的构造函数,以便子类访问父类的方法和属性。您可以使用super()方法来完成此操作
相关问题 更多 >
编程相关推荐