简体   繁体   中英

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

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(self.name)  #not working 

Obj=Parent()

Obj.func1("ram")

Obj2=Child()

Obj2.func2()

Your Obj and Obj2 are distinct instances of two distinct classes. By calling Obj.func1("ram") you set name in Obj and it will not have any effect to Obj2 . These instances have both different type and 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=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. Then you can access the "name" attribute using Parent class.

Hope this helps. It is working in my machine.

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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