简体   繁体   English

INHERITANCE (PYTHON) - 无法访问子 class 中的“名称”,但能够访问方法和 class 属性

[英]INHERITANCE (PYTHON) -not able acess 'name' in child class but able to access method and class attributes

class Parent: country="India" class 父级:country="India"

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

class Child(Parent): Company="BMW" class 孩子(父母):公司=“宝马”

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

Obj=Parent()对象=父()

Obj.func1("ram") obj.func1("ram")

Obj2=Child() obj2=孩子()

Obj2.func2() obj2.func2()

Your Obj and Obj2 are distinct instances of two distinct classes.您的ObjObj2是两个不同类的不同实例。 By calling Obj.func1("ram") you set name in Obj and it will not have any effect to Obj2 .通过调用Obj.func1("ram")您在Obj中设置name ,它不会对Obj2产生任何影响。 These instances have both different type and ID:这些实例具有不同的类型和 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>

If you want to set Obj2.name , you have to call Obj2.func1("ram") before Obj2.func2() :如果要设置Obj2.name ,则必须在 Obj2.func2() 之前调用Obj2.func1("ram") Obj2.func2()

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

If you want to access the "name" attribute of Parent class then create it explicitly outside the class definition.如果要访问父 class 的“名称”属性,则在 class 定义之外显式创建它。 Then you can access the "name" attribute using Parent class.然后,您可以使用父 class 访问“名称”属性。

Hope this helps.希望这可以帮助。 It is working in my machine.它在我的机器上工作。

Thank you.谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM