BORUSSEN11 BORUSSEN11 - 1 month ago 9
Python Question

get object from another class

I'm trying to get an object from class B in class A because the class A is composed by object of class B:

ObjectClassB = [ObjectCLassA1,ObjectClassA2,ObjectClassA3]


with ObjectClassA are sublists of Class B.

With this code I'm trying to add an element to one object of Class B to get this result:

[[1, 2, 3], [3, 4, 5], [6,7,8]]




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

class A: # the class A is a composed from many object of B
def __init__(self):
self.ls=[]
self.lst=[[1,2,3],[3,4,5]] #
def __str__(self):
return str(self.lst)
def __repr__(self):
return str(self.__dict__)

def add(self,X,Y,Z): # trying to add b object to the list
b=B(X,Y,Z)
print(b)
self.ls.append(b)
self.lst.append(self.ls)
print(self.lst)
#### TEST####
objA=A()
objA.add(6,7,8)


When I execute this test I get for
print(b)
:

>>> <__main__.B instance at 0x1d8ab90>


and for
print(self.lst)
:

>>> [[1, 2, 3], [3, 4, 5], [...]]


How can I fix this?

Answer

The problem there is that you are trying to print an object. print(b) will print the address of the object in memory since it can't infer what should be printed.

class B: 
    def __init__(self,X,Y,Z):
        self.X=X
        self.Y=Y
        self.Z=Z
    def Xreturner(self):
        return self.X
    def Yreturner(self):
        return self.Y
    def Zreturner(self):
        return self.Z
    def listReturner(self):
        return [self.X, self.Y, self.Z] #return a list ready to be added

class A: # the class A is a composed from many object of B
    def __init__(self):
        self.ls=[]
        self.lst=[[1,2,3],[3,4,5]] # 
    def __str__(self):
        return str(self.lst)
    def __repr__(self):
        return str(self.__dict__) 

    def add(self,X,Y,Z): # trying to add b object to the list
        b=B(X,Y,Z)
        print(b) #Will print the address of b
        print(b.X) #Will print the value of X in b
        self.ls.append(b)

        self.ls.append([b.X, b.Y, b.Z]) ### EDIT: this will add the desired values to the list

        print(self.ls) #Will print the addresses of the objects in the list
        print([a.X for a in self.ls]) #Will print the values of X for each object in the list
        self.lst.append(self.lst) #This line might be wrong
        print(self.lst)
#### TEST####
objA=A()
objA.add(6,7,8)
Comments