Python不同类'对象的列表

时间:2014-02-27 17:28:36

标签: python class

您好我已经在Python中声明了一个类,然后我想创建这个类的对象列表并打印它。我是python的新手,我无法弄清楚我做错了什么。我知道C ++,这就是我想做的事情

class Word:

    def __init__(self,word,hor):
        self.word=word
        self.x1=0
        self.y1=0
        self.x2=0
        self.y2=0
        self.hor=hor

    def get_dimensions(self):
        return(self.x1,self.y1,self.x2,self.y2)

    def set_dimensions(self,t):
        self.x1=t[0]
        self.y1=t[1]
        self.x2=t[2]
        self.y2=t[3]

    def get_horizontal():
        return self.hor

    def display(self):
        print word

def WordList(word_list,hor):
    l=[]
    for x in word_list:
        w1=Word(x,hor)
        l.append(w1)
    return l


li=["123","23","43"]
li=WordList(li,True)
for x in li:
    x.display #obviously something else has to be done here

当我尝试运行它时,我也遇到以下编译问题:

[<__main__.Word instance at 0x7ffc9320aa70>, <__main__.Word instance at 0x7ffc9320ab00>, <__main__.Word instance at 0x7ffc9320ab48>]

你能帮助我吗?

2 个答案:

答案 0 :(得分:2)

您需要修复两个错误:

def display(self):
    print self.word #Added self here

for x in li:
    x.display() #Added brackets here

答案 1 :(得分:2)

您正在尝试打印方法本身,而不是调用它。

请改用以下内容:

for x in li:
    x.display()

您还可以提供自定义 str 方法;

class SomeClassHere(object):
    def __init__(self, a):
        self.a = a
    def __str__(self):
        return "Hello %s" % ( self.a, )

>>> a = SomeClassHere(a="world")
>>> print a
Hello world

回答有关类型是否匹配的其他问题;

>>> class Hello(object):
...     def __init__(self, a):
...         self.a = a
... 
>>> b = Hello(a=1)
>>> c = Hello(a=2)
>>> d = Hello(a=3)
>>> b == c
False
>>> c == d
False
>>> isinstance(b, Hello)
True

您可以通过修改__eq____cmp__来更改此行为 - 请参阅:

How is __eq__ handled in Python and in what order?