我有一個物件類:
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")
但是我不想這樣做,因為它需要很多特殊的代碼支持才能運行。
uj5u.com熱心網友回復:
一個解決方案是讓你的類成為 str 的子類。這類似于How to make a class that act like a string?
修改后的代碼
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496277.html
標籤:Python python-2.7 目的 代表 对象类
上一篇:如何在Dash中使用按鈕在多個選項卡之間切換,以及如何在單擊一次后重置按鈕?
下一篇:使用arcpy從欄位中獲取變數