Python:获取类的方法,属于哪个方法

问题描述:

python类方法是否有方法/成员本身,它表示类,它们属于?Python:获取类的方法,属于哪个方法

例如...:

# a simple global function dummy WITHOUT any class membership 
def global_function(): 
print('global_function') 

# a simple method dummy WITH a membership in a class 
class Clazz: 
def method(): 
    print('Clazz.method') 

global_function() # prints "global_function" 
Clazz.method() # prints "Clazz.method" 

# until here, everything should be clear 

# define a simple replacement 
def xxx(): 
print('xxx') 

# replaces a certain function OR method with the xxx-function above 
def replace_with_xxx(func, clazz = None): 
if clazz: 
    setattr(clazz, func.__name__, xxx) 
else: 
    func.__globals__[func.__name__] = xxx 

# make all methods/functions print "xxx" 
replace_with_xxx(global_function) 
replace_with_xxx(Clazz.method, Clazz) 

# works great: 
global_function() # prints "xxx" 
Clazz.method() # prints "xxx" 

# OK, everything fine! 
# But I would like to write something like: 
replace_with_xxx(Clazz.method) 
# instead of 
replace_with_xxx(Clazz.method, Clazz) 
# note: no second parameter Clazz! 

现在我的问题是:怎么可能,让所有方法/函数调用印刷“XXX”,没有“clazz中=无”的说法replace_with_xxx功能???

有什么可能,如:

def replace_with_xxx(func): # before it was: (func, clazz = None) 
if func.has_class(): # something possible like this??? 
    setattr(func.get_class(), func.__name__, xxx) # and this ??? 
else: 
    func.__globals__[func.__name__] = xxx 

非常感谢您的阅读。我希望我能说清楚一点,我想要什么。祝你今天愉快! :)

+3

多么可怕的想法。你为什么试图修改一个类的结构?为什么不定义一个新班级?为什么不使用像** Strategy **这样更简单的设计模式? – 2011-01-29 03:56:38

我不认为这是可能的,作为一个简单的解释,为什么我们应该考虑以下几点:您可以定义一个函数并将其附加到类,没有任何附加声明,它会被存储为的一个领域类。您可以将相同的功能作为类方法分配给2个或更多不同的类。

所以方法不应该包含关于类的任何信息。

Clazz.method将有一个属性im_class,它会告诉你的类是什么。

但是,如果你发现自己想要做到这一点,这可能意味着你正在做的事情的艰辛的道路。我不知道你在做什么,但是除非你没有别的选择,否则这是一种非常糟糕的做法。

对于包装在@classmethod中的方法,该方法将被绑定并包含指向该类的引用im_self