Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: accessing attributes and methods of one class in another

Tags:

python

oop

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 ?

like image 906
bhaskarc Avatar asked Jun 29 '13 18:06

bhaskarc


People also ask

How do you use attributes of one class in another class Python?

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.

What is a used to access the attributes and methods of the class in Python?

getattr() − A python method used to access the attribute of a class.

How do you use a variable from another class in Python?

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.

How do you access other members of a class from within a class in Python?

In Python, we use a dot (.) operator to access the members of a class.


1 Answers

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.

like image 171
Martijn Pieters Avatar answered Oct 21 '22 17:10

Martijn Pieters