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

时间:2016-04-24 01:38:16

标签: 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_containing_class'实际上对它所在的A实例做一些事情,所以如果它改变某些东西,它也可用于b2。

是否有类或语法?

3 个答案:

答案 0 :(得分:1)

在B中有一个指向其父实例A

的实例变量

答案 1 :(得分:1)

正如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 = ...

答案 2 :(得分:0)

试试这个

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'
    """
    ...