繁体   English   中英

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

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

class 父级:country="India"

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

class 孩子(父母):公司=“宝马”

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

对象=父()

obj.func1("ram")

obj2=孩子()

obj2.func2()

您的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.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()

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

希望这可以帮助。 它在我的机器上工作。

谢谢你。

暂无
暂无

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

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