Reputation: 1063
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
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
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
Reputation: 2172
Have an instance variable in B that points to its parent instance of A
Upvotes: 1