我正在尝试编写一个对象,该对象具有返回函数的 getCallable()
方法。我想将此函数作为类属性提供,这样我就可以继承我的父类并为每个子类设置不同的函数。
在我的例子中,该对象是一个带有交互式输入字段的小部件,用户可以填写该字段以设置大部分功能参数。
问题是该函数似乎被视为实例方法,实例在调用时作为第一个参数传递。
这是为什么呢?如何修改我的代码以使实例不作为函数属性传递?
这是一个重现我的问题的非常简化的示例:
def mult(a, b):
return a * b
class MultiplierFilter(object):
function = mult
def __init__(self):
super().__init__()
self.multiplier = 1
def parameters(self):
return {
"multiplier": self.multiplier}
def setParameters(self, params):
"""
:param dict params:
:return:
"""
self.multiplier = params.get("multiplier", 1)
def getCallable(self):
"""Return a function that takes a number as only argument and returns
another number.
"""
mult = self.multiplier
def f(value):
return self.function(value, mult)
return f
if __name__ == '__main__':
multiplier_object = MultiplierFilter()
multiplier_object.setParameters({"multiplier": 2})
test_function = multiplier_object.getCallable()
print(test_function(7.))
错误信息:
Traceback (most recent call last):
File "C:/Users/Pierre/PycharmProjects/pyipsdk_tuto/2.py", line 39, in <module>
print(test_function(7.))
File "C:/Users/Pierre/PycharmProjects/pyipsdk_tuto/2.py", line 30, in f
return self.function(value, mult)
TypeError: mult() takes 2 positional arguments but 3 were given
最佳答案
函数的定义方式并不重要;它只是 class
定义末尾类的命名空间中的一个函数,因此被视为您在此处定义的任何其他函数。 class
block 是功能齐全的 Python 代码,唯一重要的是 block 末尾的结果是什么。
你想要的是用staticmethod
装饰函数:
class MultiplierFilter:
function = staticmethod(mult)
这将防止 self
在调用时被隐式传递。
关于python - 为什么分配给类属性的函数被视为实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56770074/