[英]How can I define a containing class for another class in python?
I want class B to be like a child of class A: 我希望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'
"""
...
I want 'do_something_with_containing_class' of b1 to actually do something to the instance of A that it's under, so if it changes something, it will also be available for b2. 我希望b1的“ do_something_with_ contains_class”实际上对其下的A实例执行某项操作,因此,如果更改了某些内容,它也可用于b2。
Is there a class or a syntax for that? 是否有一个类或语法?
在B中有一个实例变量指向其父实例A
As Natecat has pointed out, give class B
a member pointing to its A
parent: 正如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 = ...
try this 尝试这个
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.