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

4

在f1中返回self会得到<__main__.Test instance at 0x11ae48d40>。我想要返回'苹果和肉桂',但我不能使用str(self)。有没有办法让我做到这一点?

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

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

1
为什么你在f1函数中没有使用“cinnamon”,却将其传递进去了? - XORcist
我想通过 return self + " and " + thing 返回一个字符串,例如:Apples and cinnamon,但是我做不到。 - user2909628
1
apples 不是 self 的字符串表示。您是否想返回 self.thing - Martijn Pieters
3个回答

5
为了使对象本身更易读,可以像这样定义__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' 

不,当调用f1()时,它仍将输出<main.Test instance ...>。尝试覆盖__repr__方法。 - XORcist
这仍然会打印<__main__.Test instance at 0xhexaddress>;当调用对象的str()方法(也就是print所做的)时才会使用__str__ - Martijn Pieters

1
你应该添加 <\p>。
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"

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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接