【问题标题】:INHERITANCE (PYTHON) -not able acess 'name' in child class but able to access method and class attributes继承(PYTHON) - 无法访问子类中的“名称”,但能够访问方法和类属性
【发布时间】:2021-06-29 21:14:38
【问题描述】:

班级家长: country="印度"

def func1(self,name):
    self.name=name
    print("hey there")
    print(name)       

类子(父): 公司="宝马"

def func2(self):
    print("comp=",self.Company)
    print(self.name)  #not working 

Obj=Parent()

Obj.func1("ram")

Obj2=Child()

Obj2.func2()

【问题讨论】:

  • Obj2 如果您在其上调用 func1 方法,则将仅具有 name 属性,因为该方法会创建该属性。在此之前,Obj2 没有 name 属性
  • 另外,您的代码中没有多重继承。
  • 啊是啊谢谢..这是一个单一的继承

标签: python oop inheritance multiple-inheritance


【解决方案1】:

您的ObjObj2 是两个不同类的不同实例。通过调用Obj.func1("ram"),您在Obj 中设置了name,它不会对Obj2 产生任何影响。这些实例具有不同的类型和 ID:

>>> type(Obj)
<class '__main__.Parent'>
>>> type(Obj2)
<class '__main__.Child'>
>>> print(Obj)
<__main__.Parent object at 0x7f64f03023d0>
>>> print(Obj2)
<__main__.Child object at 0x7f64f03022b0>

如果你想设置Obj2.name,你必须在Obj2.func2()之前调用Obj2.func1("ram")

>>> Obj2=Child()
>>> print(Obj2.name)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Child' object has no attribute 'name'
>>> Obj2.func1("ram")
hey there
ram
>>> print(Obj2.name)
ram

【讨论】:

  • 哦,谢谢,起初我也是这么想的,但是因为我们是继承的,所以我认为也可以继承这些实例
  • 嗨。您正在继承父类的方法,而不是从父类创建的实例的内部状态。
【解决方案2】:
class Parent:
    country = "India"

    def func1(self, name):
        self.name = name
        print("hey there")
        print(name)

class Child(Parent):
    Company="BMW"

    def func2(self):
        print("comp=",self.Company)
        print(Parent.name) # access the attribute of Parent class

Obj=Parent()

Obj.func1("ram")

Parent.name = "ram" # explicitly create an attribute for Parent class

Obj2=Child()

Obj2.func2()

如果您想访问父类的“名称”属性,则在类定义之外显式创建它。然后您可以使用 Parent 类访问“名称”属性。

希望这会有所帮助。它在我的机器上运行。

谢谢。

【讨论】:

    猜你喜欢
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2013-09-27
    • 1970-01-01
    相关资源
    最近更新 更多