简体   繁体   English

从对象列表中获取价值

[英]Getting value from a list of objects

I try to write a program which will generate me all possible combinations of positions in given range of X and Y. For example: [A1,A2,A3,B1,...] As I am new to OOP I have some problem with printing these values. 我尝试编写一个程序,它将在给定的X和Y范围内生成所有可能的位置组合。例如:[A1,A2,A3,B1,...]由于我是OOP的新手,所以我遇到了一些问题打印这些值。 Below is my code: 下面是我的代码:

X = ['A','B','C']  
Y = ['1','2','3']

class Combination:
    def __init__(self,x,y):
        if (x in X) and (y in Y):
            self.x = x
            self.y = y
        else:
            print "WRONG!!"

    def __str__ (self):
        return x+y

class Position:
    def __init__(self):
        self.xy = []
        for i in X:
            for j in Y:
                self.xy.append(Combination(i,j))
    def __str__(self):
        return "List contains: " + str(self.xy)

P1 = Position()
print P1

My result is: 我的结果是:

List contains: [<__main__.Combination object>, <__main__.Combination object>,....

As I mentioned, I would like to see something like that: [A1,A2,A3,B1,...] If I change line: 正如我提到的,我希望看到类似的内容:[A1,A2,A3,B1,...]如果我更改行:

 self.xy.append(Combination(i,j))

to: 至:

 self.xy.append(i,j)

It works fine but I want to use class Combination there. 它工作正常,但我想在那里使用Class Combination。

Does anyone know how to do it? 有人知道怎么做吗? What is wrong here? 怎么了

In the Combinations class, you need to define __repr__ method, instead of __str__ like this Combinations类中,您需要定义__repr__方法,而不是像这样的__str__

def __repr__ (self):
    return self.x+self.y

with this change, the output is 进行此更改后,输出为

List contains: [A1, A2, A3, B1, B2, B3, C1, C2, C3]

Your Combination __str__ method needs improving. 您的__str__组合方法需要改进。 Firstly, I suspect it should be __repr__ and secondly it needs self.x + self.y 首先,我怀疑应该是__repr__ ,其次它需要self.x + self.y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM