make __str __或__repr__返回列表作为字符串

时间:2014-04-06 09:02:44

标签: python python-3.x python-3.3

我正在使用python 3.3.4。这是我的代码:

class ojaxi(object):
    nomeri = 0
    def __init__(self):
        self.wevri = []

    def damateba(self, adamiani):
        if adamiani in self.wevri:
            print("We Already Have That one")
        else:
            self.wevri.append(adamiani)

    def __repr__(self):
        return self.wevri



class adamiani(ojaxi):
    def __init__(self, saxeli, shuasax, asaki):
        self.saxeli = saxeli
        self.shuasax = shuasax
        self.asaki = asaki

    def __str__(self):
        return self




baramidze = ojaxi()
N1 = adamiani("tyler", "durden", 18)
N2 = adamiani("joe", "black", 20)
baramidze.damateba(N1)
baramidze.damateba(N2)


print(baramidze)

我遇到的问题是,我无法打印出功能,打印出" baramidze"中的所有成员。我希望__repr____str__打印出类似这样的内容: ["N1", "N2"]

我得到的是一个错误说:

__str__ returned non-string (type list)

2 个答案:

答案 0 :(得分:1)

如错误所示,您必须从__str__返回一个字符串。要做你想做的事你可能会喜欢这个:

def __str__(self):
    return repr(self.wevri)

答案 1 :(得分:0)

你应该这样做:

def __str__(self):
    return ' '.join(self.saxeli+self.shuasax+str(self.asaki))