我想制作一個執行以下操作的腳本:
class Foo():
def magic_method(...):
return called_function
a = Foo()
a.bar()
> bar
a.foo()
> foo
所以基本上,如果 Foo() 中不存在該方法,則不要回傳錯誤,而是接受它并將其用作字串來執行其他操作。
這在python中可能嗎?
uj5u.com熱心網友回復:
您可以覆寫__getattr__魔術方法:
class Foo():
def __getattr__(self, name):
return lambda: name
現在:
>>> a = Foo()
>>> a.something()
'something'
您需要回傳,lambda因此呼叫會.something()回傳方法的名稱(而不僅僅是.something)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346958.html
上一篇:如何從Python(3.9)中的字串中提取特定字母之間的文本?
下一篇:洗掉使用合并資料框創建的列
