這個問題在這里已經有了答案: python內置型別的擴展方法 5個回答 8 小時前關閉。
我想為str資料型別創建新方法。這是我嘗試過的
class str(str):
def __init__(self) -> None:
super().__init__()
def work(self):
# Just for testing
print("works")
在這里,當我使用此作品初始化字串str()但將它們包裹在簡單的引號中時,這會引發錯誤AttributeError: 'str' object has no attribute 'work'
像這樣:
b = str("Hello world")
b.work()
使用標準輸出按預期作業 "works"
但,
a = "Hello world"
a.work()
加注 AttributeError: 'str' object has no attribute 'work'
我想創建新方法,以便它們適用于這些情況:
"foo".work()
str("foo").work() # <- This actually works :D
bar = "foo"; bar.work()
謝謝您的幫助。
uj5u.com熱心網友回復:
這是無法做到的,因為str它是 Python 中的不可變型別之一。不可變型別包括bool, int, float, tuple, string,frozenset也許還有一些我不知道的型別。
對于其他型別,您可能可以執行以下操作:
class MyClass:
def __str__(self):
return "my class"
def print_me_quoted(self):
print(f'"{self}"')
mc_old = MyClass()
MyClass.print_me_quoted = print_me_quoted
mc_new = MyClass()
# both now have it
mc_old.print_me_quoted()
mc_new.print_me_quoted()
像這樣通過猴子修補來改變一個類的行為仍然是一個非常糟糕的主意,但它可以做到。期望您的編輯器或 IDE 不喜歡它或不理解它 - 您會看到警告。
如果你嘗試這個str:
def print_me_quoted(self):
print(f'"{self}"')
str.print_me_quoted = print_me_quoted
mc = str(10)
mc.print_me_quoted()
你得到這個TypeError:
TypeError: cannot set 'print_me_quoted' attribute of immutable type 'str'
你可以在你自己的版本上做到這一點str:
class Str(str):
...
def print_me_quoted(self):
print(f'"{self}"')
Str.print_me_quoted = print_me_quoted
mc = Str(10)
mc.print_me_quoted()
但這當然不會改變字串的標準行為——這正是重點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412107.html
標籤:
