繁体   English   中英

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

[英]How to return string representation of self in a class in Python?

在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")

要“漂亮地打印”对象本身,请定义__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' 

您应该添加

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"

如果您希望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'

暂无
暂无

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

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