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


慕少森
浏览 71回答 4
4回答

森林海

从超类继承后,必须调用父类的__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)输出: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.xOut[1830]: 'dangerous'

Qyouu

为了让子类访问父类的方法和属性,需要在子类的构造函数中调用父类的构造函数。您可以借助 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)

手掌心

Python 中的方法与 C++ 或 Java 等真正的 OOP 语言不同。不存在在类定义中直接声明属性以使该属性自动成为实例属性的情况:class A:    an_attribute = 0是类an_attribute的属性,但不是该类实例的属性: Aa = A()                     # an instance of the class Aprint(a.an_attribute)       # 0 - so IS the an_attribute an instance's attribute?看起来这an_attribute就是实例的属性,但是......A.an_attribute = 100        # changing the value of a CLASS attributeprint(a.an_attribute)       # 100; so it is NOT the independent OBJECT 's attribute那么如何创建一个对象的属性呢?好简单:a.an_attribute = 200        # creating an OBJECT's attributeprint(a.an_attribute)       # 200 — the OBJECT's attribute, independent of a CLASS' oneprint(A.an_attribute)       # 100 — the CLASS attribute从这一刻起,对象a就有了自己的属性,不同于同名的类属性。这意味着同一类的不同实例不仅可以具有相同属性的不同值,甚至可以具有完全不同的属性:b = A()b.different_attribute = 500非常奇怪的情况:该对象a具有属性,但同一个类的an_attribute对象没有,b对象b具有属性different_attribute ,但对象a没有。有没有办法在类定义中规定/初始化实例的属性?幸运的是,有一个特殊的方法__init__(),当您创建类的实例时,它会自动运行,并自动接收刚刚创建的对象作为其第一个参数(通常称为this)。因此,您可以使用此自动填充的参数为刚刚创建的对象分配一个属性:class A:    def __init__(self):        self.an_attribute = 20        self.different_attribute = 50现在,该类的所有新实例都A将拥有自己的对象属性 an_attribute和different_attribute(分别用值20和初始化50,这在这里并不重要)。因此,实例变量不会自动被子类继承。其他人已经解释了如何绕过它 - 毫不奇怪在内置函数__init__()的帮助下使用子类的方法。super()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python