1 回答

TA貢獻1841條經驗 獲得超3個贊
頭部不是一種身體,它是身體的一部分AFAIK。
所以你應該使用組合而不是繼承:
class Head:
def __init__(self):
# ...Set-up head...
def head_actions():
print('Head does something')
class Body:
def __init__(self):
self.head = Head()
# ...Set-up body...
def body_actions:
print('Body does something')
現在你可以這樣做:
body = Body()
body.body_actions()
body.head.head_actions()
你得到無限遞歸的原因是你Body是 的超類Head,所以當你調用super().__init__()你實例化 a 時Body,它在你的實現中創建了 a Head,它調用super().__init__()等等。
組合(如果這就是“嵌套”的意思)不是壞習慣,它是標準做法,通常比繼承更有意義。
編輯以回應評論
要從 訪問Body方法,Head您可以傳遞Body對創建時的引用。所以重新定義類如下:
class Head:
def __init__(self, body):
self.body = body
def head_actions():
print('Head does something')
class Body:
def __init__(self):
self.head = Head(self)
def body_actions:
print('Body does something')
現在您可以從身體訪問頭部,從頭部訪問身體:
body = Body()
head = body.head
head.body.body_actions()
甚至
body.head.body.body_actions()
添加回答
舉報