2013-02-04 103 views
0

我有類:如何在Python中獲取調用方法的名稱(動態添加)?

class SimpleClass: 
    def __init__(self): 
     pass 

    def init_levels(self): 
     levels = get_levels_list() 
     for level in levels: 
      Transplant(foo, Simplelog, method_name=level) 

移植是動態的添加方法類的類:

class Transplant: 
    def __init__(self, method, host, method_name=None): 
     self.host = host 
     self.method = method 
     self.method_name = method_name 
     setattr(host, method_name or method.__name__, self) 

    def __call__(self, *args, **kwargs): 
     nargs = [self.host] 
     nargs.extend(args) 
     return apply(self.method, nargs, kwargs) 

富是 「移植」 功能:

def foo(self): 
    return 

我怎樣才能在foo裏面調用方法名稱?

比如我執行:

simpleinst = SimpleClass() 
simpleinst.init_levels() 

如何修改我的代碼爲FOO定義體越來越被調用的方法的名字嗎?

回答

2

你必須明確傳遞:

class Transplant: 
    def __init__(self, method, host, method_name=None): 
     self.host = host 
     self.method = method 
     self.method_name = method_name or method.__name__ 
     setattr(host, method_name or method.__name__, self) 

    def __call__(self, *args, **kwargs): 
     nargs = [self.host, self.method_name] 
     nargs.extend(args) 
     return apply(self.method, nargs, kwargs) 

並延長foo接受這個參數。

+0

謝謝!我只是將nargs = [self.host]替換爲nargs = [self],現在我擁有所有的方法參數。 – SkyFox

+0

更好。 :-) –

0

你可以用一個函數工廠做,make_foo

的關鍵步驟是重新定義函數的func_name屬性:

foo.func_name = name 

class SimpleClass: 
    def init_levels(self): 
     levels = ['foo', 'bar'] 
     for level in levels: 
      # Your original code defined this on `SimpleLog`. Did you mean `SimpleClass`? 
      setattr(SimpleClass, level, make_foo(level)) 

def make_foo(name): 
    def foo(self): 
     print('{n} has been called'.format(n = foo.func_name)) 

    foo.func_name = name 
    return foo 

simpleinst = SimpleClass() 
simpleinst.init_levels() 
simpleinst.foo() 
# foo has been called 
simpleinst.bar() 
# bar has been called 
相關問題