Search code examples
pythoncomposition

Can't access instance attributes


I try to use the composition relationship but I can't access to the compound class A: with this code I'm trying to add to the list of class A, an object from the class B.

class B:
    def __init__(self,X,Y,Z):
        self.X
        self.Y
        self.Z
    def Xreturner(self):
        return self.X
    def Yreturner(self):
        return self.Y
    def Zreturner(self):
        return self.Z

class A:
    def __init(self):
        self.lst=[[1,2,3],[3,4,5],]
        self.b=B()
    def add(self): # trying to add b object to the list
        self.lst.append(self.b)
#### TEST####
objA=A()
objA.add(6,7,8)

When I test I get this error:

Traceback (most recent call last):
  File "home/testXYZ.py", line 28, in <module>
    objA.add(6,7,8)
TypeError: add() takes exactly 1 argument (4 given)

Please help me to solve this.


Solution

  • First, your class B initializer is incorrect:

    class B:
        def __init__(self, x, y, z):  # <== should use snake_case for vars
            self.x = x
            self.y = y
            self.z = z
    

    Next, your class A add should create a new B object and add to the list:

        def add(self, x, y, z):
            new_b = B(x, y z)
            self.lst.append(new_b)