2016-05-07 49 views
1

之外我有我想利用任意方法在初始化时使用根据上下文字符串解析类。错误使用类方法定义

使用类以外定义的方法,这里讨论: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? 有没有一种方法来定义函数,出现这种情况,还是我需要自我参数明确传递给外部类定义为这样的方法:

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) 
+0

哎哟,这很棘手。我有类似的东西,不能找到一个解决办法:( – linusg

回答

1

您必须包装在函数传递在“MethodType”中。

从你的初始化中:

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

这种结合的方法的类,并允许它接受隐自我参数。确保你的脚本的顶部有import types

+0

不胜感激,谢谢! – Dan

+0

另一种选择是将其包装在'functools.partial()'或对您通过自己的λ。 – Kevin

相关问题