为了账号安全,请及时绑定邮箱和手机立即绑定

Python:从子类访问父属性

Python:从子类访问父属性

慕少森 2023-12-26 16:39:57
在 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
查看完整描述

4 回答

?
森林海

TA贡献2011条经验 获得超2个赞

从超类继承后,必须调用父类的__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


查看完整回答
反对 回复 2023-12-26
?
弑天下

TA贡献1818条经验 获得超7个赞

您可以使用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'


查看完整回答
反对 回复 2023-12-26
?
Qyouu

TA贡献1786条经验 获得超11个赞

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


查看完整回答
反对 回复 2023-12-26
?
手掌心

TA贡献1942条经验 获得超3个赞

Python 中的方法与 C++ 或 Java 等真正的 OOP 语言不同。


不存在在类定义中直接声明属性以使该属性自动成为实例属性的情况:


class A:

    an_attribute = 0

是类an_attribute的属性,但不是该类实例的属性: A


a = A()                     # an instance of the class A

print(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 attribute

print(a.an_attribute)       # 100; so it is NOT the independent OBJECT 's attribute

那么如何创建一个对象的属性呢?好简单:


a.an_attribute = 200        # creating an OBJECT's attribute


print(a.an_attribute)       # 200 — the OBJECT's attribute, independent of a CLASS' one

print(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()


查看完整回答
反对 回复 2023-12-26
  • 4 回答
  • 0 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信