我正在嘗試將 python 類變數用作函式,使用類似于以下代碼的內容:
class A(object):
func = None
@classmethod
def class_init(c,f):
c.func = f
def go(self, p):
A.func(p)
def my_print(p):
print(p)
A.class_init(my_print)
a = A()
a.go('AAA')
使用 python3 運行它時,一切都按預期作業并被AAA列印出來。
使用python2,TypeError拋出例外:
TypeError: unbound method my_print() must be called with A instance as first argument (got str instance instead)
似乎 python2 需要一個類實體,就好像它A.func是一個物件方法一樣。
是什么導致了 python2 和 python3 之間的這種不同行為?
有沒有辦法“告訴”pythonA.func作為非物件方法處理?
[我可以想到像另存A.func為串列這樣的解決方法,意思是c.func = [f]inclass_init和以后A.func[0](p),go但想了解這種行為的核心原因以及是否有一個簡潔的解決方案]
uj5u.com熱心網友回復:
由于您要添加的函式不采用類實體或類作為其第一個引數,顯然您正在添加一個靜態方法 - 所以您必須通過手動呼叫內置的來明確告訴 Python 您正在做什么 -在staticmethod()功能上。
class A(object):
func = None
@classmethod
def class_init(c, f):
c.func = staticmethod(f) # Assume function type.
def go(self, p):
A.func(p)
def my_print(p):
print(p)
A.class_init(my_print)
a = A()
a.go('AAA') #-> AAA
my_print(42) # -> 42
或者,您可以在類之外使用它作為函式裝飾器,如下所示。這樣做的一個缺點是它只能通過類或類實體呼叫。
class A(object):
func = None
@classmethod
def class_init(c, f):
c.func = f
def go(self, p):
A.func(p)
@staticmethod
def my_print(p):
print(p)
A.class_init(my_print)
a = A()
a.go('AAA') # -> AAA
my_print(42) # -> TypeError: 'staticmethod' object is not callable
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443964.html
標籤:Python python-2.7
上一篇:需要想法如何決議以下JSON格式
