关于班级和学校__

2024-03-28 12:12:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'

Tags: 实例字符串selfnewreturnifobjectinit
3条回答

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

print str(new) + '.kine'

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

重写__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

尝试显式转换为字符串:

print str(new) + '.kine'

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

print '{}.kine'.format(new)

相关问题 更多 >