簡體   English   中英

將外部函數分配給 Python 中的類變量

[英]Assign external function to class variable in Python

我正在嘗試將在別處定義的函數分配給類變量,以便稍后可以在實例的方法之一中調用它,如下所示:

from module import my_func

class Bar(object):
    func = my_func
    def run(self):
        self.func()  # Runs my function

問題是這失敗了,因為在執行self.func() ,實例作為第一個參數傳遞。

我想出了一個黑客,但對我來說似乎很難看,有人有其他選擇嗎?

In [1]: class Foo(object):
   ...:     func = lambda *args: args
   ...:     def __init__(self):
   ...:         print(self.func())
   ...:

In [2]: class Foo2(object):
   ...:     funcs = [lambda *args: args]
   ...:     def __init__(self):
   ...:         print(self.funcs[0]())
   ...:

In [3]: f = Foo()
(<__main__.Foo object at 0x00000000044BFB70>,)

In [4]: f2 = Foo2()
()

編輯:行為與內置函數不同!

In [13]: from math import pow

In [14]: def pow_(a, b):
   ....:     return pow(a, b)
   ....:

In [15]: class Foo3(object):
   ....:     func = pow_
   ....:     def __init__(self):
   ....:         print(self.func(2, 3))
   ....:

In [16]: f3 = Foo3()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-c27c8778655e> in <module>()
----> 1 f3 = Foo3()

<ipython-input-15-efeb6adb211c> in __init__(self)
      2     func = pow_
      3     def __init__(self):
----> 4         print(self.func(2, 3))
      5

TypeError: pow_() takes exactly 2 arguments (3 given)

In [17]: class Foo4(object):
   ....:     func = pow
   ....:     def __init__(self):
   ....:         print(self.func(2, 3))
   ....:

In [18]: f4 = Foo4()
8.0

Python 函數是描述符對象,當類的屬性訪問它們時,實例會導致它們被綁定為方法。

如果要防止這種情況發生,請使用staticmethod函數函數包裝在不綁定到實例的不同描述符中:

class Bar(object):
    func = staticmethod(my_func)
    def run(self):
        self.func()

或者,通過方法上的__func__屬性訪問未綁定的函數:

def run(self):
    self.func.__func__()

或直接轉到類__dict__屬性以完全繞過描述符協議:

def run(self):
    Bar.__dict__['func']()

至於math.pow ,那不是Python函數,因為它是用 C 代碼編寫的。 大多數內置函數是用 C 編寫的,大多數不是描述符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM