【问题标题】:Error Using Class Method Defined Outside of Class使用在类之外定义的类方法时出错
【发布时间】:2016-09-02 14:31:32
【问题描述】:

我有一个类,我想在初始化时采用任意方法来根据上下文进行字符串解析。

使用在此处讨论的类之外定义的方法:Python define method outside of class definition?

def my_string_method(self):
    return self.var.strip()

class My_Class():
    def __init__(self, string_method):
        self.var = ' foo '
        self.string_method = string_method

    def use_string_method(self):
        return self.string_method()

instance = My_Class(string_method=my_string_method)
print instance.use_string_method()

我收到错误“TypeError: use_string_method() takes exactly 1 argument (0 given)”。

不应该将self 参数隐式传递给use_string_method 吗? 有没有办法定义函数以使这种情况发生,或者我是否需要将 self 参数显式传递给在类外部定义的方法:

class My_Class():
    def __init__(self, string_method):
        self.var = ' foo '
        self.string_method = string_method

    def use_string_method(self):
        return self.string_method(self)

【问题讨论】:

  • 哎呀,这很棘手。我有类似的东西,找不到解决方法:(

标签: python class methods


【解决方案1】:

您必须将传入的函数包装在“MethodType”中。

在你的初始化中:

self.string_method = types.MethodType(string_method, self)

这将方法绑定到类并允许它接收隐式 self 参数。确保 import types 在脚本的顶部。

【讨论】:

  • 另一种选择是将其包装在 functools.partial() 或为您传递 self 的 lambda 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多