从另一个类获取对象

时间:2016-11-03 18:03:17

标签: python composition

我试图从A类的B类中获取一个对象,因为A类是由B类的对象组成的:

ObjectClassB = [ObjectCLassA1,ObjectClassA2,ObjectClassA3] 
使用ObjectClassA的

是B类的子列表。

使用此代码,我尝试将一个元素添加到B类的一个对象中以获得此结果:

[[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)

当我执行此测试时,我得到print(b)

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

print(self.lst)

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

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

问题是您正在尝试print一个对象。 print(b)将在内存中打印对象的地址,因为它无法推断应该打印的内容。

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)

答案 1 :(得分:0)

正如所指出的那样,你的代码(或多或少:更多)正确地做事,而你真正需要解决的是class B 向世界展示的方式。打印。为此,您可以向__repr__添加class B方法,以解决此问题。

我看到的另一个问题是self.lst.append(self.ls),它会在列表lst中附加一个列表列表。我想你可以跳过它,然后运行self.lst.append(b)并完成。

请注意,self.lst的{​​{1}}中的前两个元素仍然是类型class A,但我想这是怎么回事你想让它发挥作用。

此处编写代码,并在https://eval.in/671341

上查看该代码
class B

答案 2 :(得分:0)

这是你想要的最小例子。

__repr__

上实施B
class B: 
    def __init__(self,X,Y,Z):
        self.X=X
        self.Y=Y
        self.Z=Z

    def __repr__(self):
        return str([self.X, self.Y, self.Z])

b1 = B(1, 2, 3)
b2 = B(3, 4, 5)

print(b1)  # [1, 2, 3]

b_list = [b1, b2]

print(b_list) # [[1, 2, 3], [3, 4, 5]]
相关问题