Let's say I have two classes A and B:
Class A:
# A's attributes and methods here
Class B:
# B's attributes and methods here
Now I can assess A's properties in object of B class as follows:
a_obj = A()
b_obj = B(a_obj)
What I need is a two way access. How do I access A's properties in B and B's properties in A ?
Just create the variables in a class. And then inherit from that class to access its variables. But before accessing them, the parent class has to be called to initiate the variables.
getattr() − A python method used to access the attribute of a class.
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.
In Python, we use a dot (.) operator to access the members of a class.
You need to create pointers either way:
class A(object):
parent = None
class B(object):
def __init__(self, child):
self.child = child
child.parent = self
Now A
can refer to self.parent
(provided it is not None
), and B
can refer to self.child
. If you try to make an instance of A
the child of more than one B
, the last 'parent' wins.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With