0

当我打印我的类的实例时,我尝试返回一个字符串值。看来这不应该像我希望的那样工作。

class oObject (object):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return str(self.value)
    def __repr__(self):
        return str(self.value)

new = oObject(50)
# if I use print it's Okay
print new
# But if i try to do something like that ...
print new + '.kine'
4

4 回答 4

3

尝试显式转换为字符串:

print str(new) + '.kine'

或者,您可以使用格式字符串:

print '{}.kine'.format(new)
于 2012-07-08T13:53:51.463 回答
2

Python 在打印之前将整个表达式的结果转换为字符串,而不是单个项目。在连接之前将您的对象实例转换为字符串:

print str(new) + '.kine'

Python 是一种强类型语言,在使用“+”号等运算符时不会自动将项目转换为字符串。

于 2012-07-08T13:54:01.337 回答
2

覆盖__add__它:

class oObject (object):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return str(self.value)
    def __repr__(self):
        return str(self.value)
    def __add__(self,val):
        return str(self.value)+val

new = oObject(50)
'''if I use print it's Okay'''
print new
'''But if i try to do something like that ...'''
print new + '.kine'   #prints 50.kine
于 2012-07-08T13:54:48.407 回答
0

试着print new看看你的.__str__()定义是否有效。内部print调用它。但是,+运算符不使用隐式转换为字符串。

于 2012-07-08T16:02:58.890 回答