Python 参数从可调用对象中消失
假设您有一个具有多个参数的函数:Python 参数从可调用对象中消失,python,python-3.x,Python,Python 3.x,假设您有一个具有多个参数的函数: def foo(x1, x2, x3, y): pass 我试图使一个名为FAI的类的行为有点像functools.partial函数 bar = my_class(foo, 1, 2, 3) bar("a") # `bar("a")` supposed to be the same as `foo(1, 2, 3, "a")` 当我运行以下代码时: def bar(*args): print(args) bar = FAI(bar, 1
def foo(x1, x2, x3, y):
pass
我试图使一个名为FAI
的类的行为有点像functools.partial
函数
bar = my_class(foo, 1, 2, 3)
bar("a")
# `bar("a")` supposed to be the same as `foo(1, 2, 3, "a")`
当我运行以下代码时:
def bar(*args):
print(args)
bar = FAI(bar, 1)
bar = FAI(bar, 2)
bar = FAI(bar, 3)
bar = FAI(bar, 4)
bar = FAI(bar, 5)
bar = FAI(bar, 6)
bar("a", "b", "c")
我得到的sys.stdout
输出是:
(1, 'a', 'b', 'c')
所需输出为以下之一:
(1, 2, 3, 4, 5, 6, 'a', 'b', 'c')
(6, 5, 4, 3, 2, 1, 'a', 'b', 'c')
如何获得所需的输出
import functools
import inspect
class Meta(type):
functools=functools
inspect=inspect
def __call__(self, imp, *args, **kwargs):
"""
instance = Klass(imp)
instance = Klass.__call__(imp)
instance = Meta.__call__(Klass, imp)
"""
# `imp`.......`implementation`
Meta = type(self)
SuperMeta = Meta.inspect.getmro(Meta)[1]
inst = SuperMeta.__call__(self, imp, *args, **kwargs)
inst = functools.update_wrapper(wrapper=inst, wrapped=imp)
return inst # instance
class FAI(metaclass=Meta):
"""
`FAI`..........`First argument inputter`
"""
def __init__(self, imp, arg):
# `imp`.......`implementation`
assert (callable(imp))
self._arg = arg
self._imp = imp
def __call__(self, *args, **kwargs):
return self._imp(self._arg, *args, **kwargs)
您正在使用
functools.update\u wrapper
。你不应该。它设计用于处理由def
定义的类型的函数,而不是任意的可调用函数
您的update\u wrapper
正在将\u arg
和\u imp
属性从旧的FAI
实例复制到新实例,因此最后一个实例具有第一个实例的\u arg
和\u imp
另外,你的Meta.\uuu调用
有我见过的super(type(self),self)
错误的最奇怪的手动实现。如果您创建了Meta
的子类(如果您不了解所使用的库,甚至可能在您没有注意到的情况下发生),SuperMeta
将是Meta
本身或其他错误的类。使用super()?您避免全局变量错误的尝试只会导致更多错误。您已经手工重新实现了常见的super(type(self),self)
bug。另外,您忘了使用functools
class属性,而是直接使用全局functools
。