[英]Prevent a function from becoming an instancemethod in Python 2
我正在編寫一些適用於Python 3但不適用於Python 2的代碼。
foo = lambda x: x + "stuff"
class MyClass(ParentClass):
bar = foo
def mymethod(self):
return self.bar(self._private_stuff)
我希望它只是打印私人的東西,但如果我嘗試運行mymethod,我得到:
TypeError: unbound method <lambda>() must be called with MyClass instance as first argument (got str instance instead)
當然,上面不是實際的代碼,而是真實的簡化。 我想這樣做是因為我需要傳遞我不想將最終用戶公開的私人信息,即擴展我的類的任何人。 但是在Python 2中,全局級lambda(或任何普通函數)成為一種instancemethod
,在這種情況下這是不需要的!
您建議我將這段代碼移植到什么位置?
最簡單的:
class MyClass(ParentClass):
bar = staticmethod(foo)
其余代碼保持不變。 雖然staticmethod
最常用作“裝飾器”,但沒有要求這樣做(因此,不需要進一步的間接級別來使bar
成為調用foo
的裝飾方法)。
我會選擇Alex Martelli的建議。 但是,僅僅為了記錄,(我在看到Alex Martelli的漂亮答案之前寫了這個答案)你也可以在Python 2.7和3.x中做到以下幾點(特別注意我提供的文檔鏈接,以便你了解發生了什么) ):
您可以使用靜態方法 ,它不會期望隱含的第一個參數。 請注意, lambda表達式不能使用語句 ,因此您將無法在2.x中的lambda
函數中使用print
語句。
foo = lambda x: x # note that you cannot use print here in 2.x
class MyClass(object):
@staticmethod # use a static method
def bar(x):
return foo(x) # or simply print(foo(x))
def mymethod(self):
return self.bar(1)
>>> m = MyClass()
>>> m.mymethod()
1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.