簡體   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