如何在Python中的类中返回self的字符串表示形式?

时间:2013-11-28 20:49:49

标签: python

在f1中返回self会给我<__main__.Test instance at 0x11ae48d40>。我希望能够返回'苹果和肉桂',但我不能做str(自我)。我有办法做到这一点吗?

class Test:
    def __init__(self, thing):
        self.thing = thing
    def f1(self, thing):
        return self + " and " + thing #<<<

a = Test("apples")
a.f1("cinnamon")

3 个答案:

答案 0 :(得分:1)

要“漂亮地打印”对象本身,请像这样定义__str__

class Test(object):
    def __init__(self, thing):
        self.thing = thing

    def __str__(self):
        return self.thing

 >>> a=Test('apple')
 >>> print a
 apple

如果您希望自定义表示形式,请添加__repr__

class Test(object):
    def __init__(self, thing):
        self.thing = thing
    def __repr__(self):
        return self.thing 

>>> Test('pear')
pear

如果要创建编辑中所述的字符串,可以执行以下操作:

class Test(object):
    def __init__(self, thing):
        self.thing = thing

    def andthis(self, other):
        return '{} and {}'.format(self.thing, other)

>>> apple=Test('apple')
>>> apple.andthis('cinnamon')
'apple and cinnamon'
>>> Test('apple').andthis('carrots')
'apple and carrots' 

答案 1 :(得分:0)

你应该添加

def __str__(self):
    return self.thing

所以它看起来像这样

class Test:
    def __init__(self, thing):
        self.thing = thing

    def f1(self, thing):
        return str(self) + " and " + thing

    def __str__(self):
        return self.thing

a = Test("apples")
print a
>> "apples"
print a.f1("orange")
>> "apples and orange"

答案 2 :(得分:0)

如果您希望f1()返回字符串,则执行此操作

def f1(self, otherthing):
    return '{} and {}'.format(self.thing, otherthing)

在这里,我们使用str.format()self.thingotherthing放在一起,返回一个新字符串。请注意,您需要在此处明确引用self.thing

您也可以使用字符串连接,就像在您自己的代码中一样:

def f1(self, otherthing):
    return self.thing + ' and ' + otherthing

但同样,您需要明确地引用self.thing

演示:

>>> class Test:
...     def __init__(self, thing):
...         self.thing = thing
...     def f1(self, otherthing):
...         return '{} and {}'.format(self.thing, otherthing)
... 
>>> a = Test("apples")
>>> a.f1("cinnamon")
'apples and cinnamon'