omer mazig
omer mazig

Reputation: 1063

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?

Upvotes: 0

Views: 40

Answers (3)

user2390182
user2390182

Reputation: 73460

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

Upvotes: 1

Ngoma Mbaku Davy
Ngoma Mbaku Davy

Reputation: 169

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

Upvotes: 0

Natecat
Natecat

Reputation: 2172

Have an instance variable in B that points to its parent instance of A

Upvotes: 1

Related Questions