Search code examples
pythonpython-3.xoopinstance-variables

Can I access a property of an object containing a list of objects of another class


Let's say I have something like this:

class A:
    def __init__(self, name, bs):
        self.aname = name
        self.bees = bs
    aname = ''
    bees = []

class B:
    def __init__(self, name):
        self.bname= name
    bname= ''
    def get_aname():
        return aname # can I get this somehow 

aobj = A('name of class A', [B('1'), B('2'), B('3')])

aobj.bees[0].get_aname()  # result should be 'name of class A'

Is there any way I could get the name of the class A?


Solution

  • aname is an instance variable. To access this from instances of B, you need to pass an instance of A to B in order for your B instance to access aname.

    But you can't pass an instance of A before it's instantiated. Instead, you can define your list of B instances and add them as an attribute of aobj in a subsequent step:

    class A:
        def __init__(self, name, bs=None):
            self.aname = name
            self.bees = bs
        aname = ''
        bees = []
    
    class B:
        def __init__(self, name, a_inst):
            self.a_inst = a_inst
            self.bname= name
        bname= ''
        def get_aname(self):
            return self.a_inst.aname
    
    aobj = A('name of class A')
    L = [B('1', aobj), B('2', aobj), B('3', aobj)]
    aobj.bees = L
    
    aobj.bees[0].get_aname()  # 'name of class A'