A 類將 B 類中的物件實體化為成員變數。這個 B 類物件如何從 A 類物件呼叫方法?當我執行下面的程式時,我希望列印一個“Hello”,但我收到一個錯誤,而不是說“name 'a' is not defined”
這里有什么問題,我該如何解決?
class B:
def __init__(self):
a.say_hello()
class A:
other = None
def __init__(self):
self.other = B()
def say_hello():
print("Helo")
a = A()
uj5u.com熱心網友回復:
Python 參考是單向的。您需要保留反向的參考才能使其正常作業。
class B:
def __init__(self, outer):
outer.say_hello()
class A:
# other = None # (see below)
def __init__(self):
self.other = B(self)
def say_hello():
print("Helo")
a = A()
如果您需要outer的不僅僅是建構式,您可以將其存盤在實體變數中。
你也不需要這other = None條線。在 Python 中,您不需要像在 Java 或 C 中那樣在類的頂部宣告實體變數。相反,您只需使用self.分配給它們,它們就會開始存在。other = None在該范圍內創建一個類變數,類似于 Java 中的靜態變數,可以被參考A.other(注意大寫A;這是類本身,而不是它的實體)。
在某些情況下,您可能希望以某種形式在類的頂部宣告實體變數(__slots__PEP 484 注釋是主要的兩個),但是對于剛開始的簡單類,沒有必要,并且這樣的分配不會達到你的預期。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411938.html
標籤:
