简体   繁体   中英

How can I define a containing class for another class in python?

I want class B to be like a child of class 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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