Skip to main content
 首页 » 编程设计

python之说服 Python 以静态方式运行保存的函数

2025年05月04日15傻小

我使用的是 Python 2.7(无法升级)。我正在尝试在我的类中存储一个函数,它可以在 ctor 中被不同的函数覆盖。该函数是一个普通的静态函数(不是成员或类方法),所以我不想在调用它时将类或对象作为第一个参数传递。出于某种原因,Python 总是将对象作为第一个参数传递。我该如何避免这种情况?

例子:

def fn(*args): 
    print str(args) 
 
class MyClass(object): 
    myfn = fn 
 
    def __init__(self, myfn=None): 
        if myfn is not None: 
            self.myfn = myfn 
 
    def run(self, arg): 
        self.myfn(arg) 
 
 
o = MyClass() 
o.run("foo") 

当我运行它时,我将对象作为 fn 的第一个参数:

$ python /tmp/testfn.py 
(<__main__.MyClass object at 0x7f7fff8dc090>, 'foo') 

如果我不添加类成员 myfn 而只是在 ctor 中分​​配值,那么它会按预期工作:

    def __init__(self, myfn=None): 
        self.myfn = fn if myfn is None else myfn 
 
$ python /tmp/testfn.py 
('foo',) 

但是,我不想这样做,因为我希望能够为整个类重置函数,以便所有 future 的对象自动获得新函数,此外还能够为单个对象重置它。

我不明白为什么类成员值的行为不同。有什么方法可以让 python 相信这个函数是一个静态函数(不要将对象作为第一个参数传递)?

请您参考如下方法:

is there any way I can convince python that this function is a static function (don't pass the object as the first argument)?

当然,只需告诉 python 它是一个 staticmethod :

class MyClass(object): 
    myfn = staticmethod(fn) 

演示:

>>> def fn(*args): 
...     print str(args) 
... 
>>> class MyClass(object): 
...     myfn = staticmethod(fn) 
...     def run(self, arg): 
...       self.myfn(arg) 
...  
>>> o = MyClass() 
>>> o.run('foo') 
('foo',)