通过 str.replace(obj_cls, "new string" 运行对象类时获取字符串



我有一个对象类:

class Color(object):
def __init__(self, color):
self.color = color

我想运行以下命令:

blue = Color("blue")
print blue
"The pen is {}".format(blue)
"The pen is blue".replace(blue, "red")

这回报:

# <__main__.Color object at 0x000001A527675908>
# The pen is <__main__.Color object at 0x000001A527675908>
# # Original exception was:
# Traceback (most recent call last):
#   File "<maya console>", line 2, in <module>
# TypeError: expected a string or other character buffer object # 

我可以通过将repr包含到类中来修复打印和格式。

class Color(object):
def __init__(self, color):
self.color = color
def __repr__(self):
return self.color
blue = Color("blue")
print blue
"The pen is {}".format(blue)
"The pen is blue".replace(blue, "red")
# blue
# The pen is blue
# # Original exception was:
# Traceback (most recent call last):
#   File "<maya console>", line 2, in <module>
# TypeError: expected a string or other character buffer object # 

如何让replace函数与这个对象类一起工作?

如果我在对象类周围放一个str()包装器,它就可以工作了:

"The pen is blue".replace(str(blue), "red")

但是我不想这样做,因为它需要很多特殊的代码支持才能运行。

一个解决方案是使您的类成为str的子类。这类似于如何使类的行为像字符串?

<修改代码/strong>

class Color(str):
def __init__(self, color):
self.color = color
def __repr__(self):
return self.color

使用

blue = Color("blue")
print("The pen is {}".format(blue))
print("The pen is blue".replace(blue, "red"))

The pen is blue
The pen is red

最新更新