[英]How can I define a containing class for another class in python?
我希望B類像A類的孩子一樣:
class A(object):
def __init__(self, id):
self.id = id
b1 = B()
b2 = B()
self.games_summary_dicts = [b1, b2]
""":type : list[B]"""
class B(object):
def __init__(self):
...
def do_something_with_containing_class(self):
"""
Doing something with self.id of A class. Something like 'self.container.id'
"""
...
我希望b1的“ do_something_with_ contains_class”實際上對其下的A實例執行某項操作,因此,如果更改了某些內容,它也可用於b2。
是否有一個類或語法?
在B中有一個實例變量指向其父實例A
正如Natecat所指出的,給B
類一個指向其A
父級的成員:
class A(object):
def __init__(self, id):
self.id = id
b1 = B(a=self)
b2 = B(a=self) # now b1, b2 have attribute .a which points to 'parent' A
self.games_summary_dicts = [b1, b2]
""":type : list[B]"""
class B(object):
def __init__(self, a): # initialize B instances with 'parent' reference
self.a = a
def do_something_with_containing_class(self):
self.a.id = ...
嘗試這個
class A (object):
def __init__(self, id):
self.id = id
b1 = B()
b2 = B()
self.games_summary_dicts = [b1, b2]
""":type : list[B]"""
class B(A):
def __init__(self):
...
def do_something_with_containing_class(self):
"""
Doing something with self.id of A class. Something like 'self.container.id'
"""
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.