繁体   English   中英

如何在python中为另一个类定义一个包含类?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM