2016-04-24 51 views
0

我想B類是象類A的孩子:如何在python中爲另一個類定義一個包含類?

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。

是否有類或語法?

回答

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 = ... 
+0

工作正常!我忘記了那些對象是通過引用而不是按值傳遞的,所以它正是我所需要的。謝謝! –

1

有B中的實例變量指向的

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

該OP的「含有」措辭是不幸的。我認爲他希望從'b2'到'A'實例的'b2'是一個成員,而不是實際的繼承。 – schwobaseggl

+0

如果問題只能通過合成解決,請避免使用繼承。 – Mikaelblomkvistsson

+0

@schwobaseggl你是對的。我只是不知道該怎麼稱呼它。 –

相關問題