2011-01-29 51 views
1

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

回答

1

我不認爲這是可能的,作爲一個簡單的解釋,爲什麼我們應該考慮以下幾點:您可以定義一個函數並將其附加到類,沒有任何附加聲明,它會被存儲爲的一個領域類。您可以將相同的功能作爲類方法分配給2個或更多不同的類。

所以方法不應該包含關於類的任何信息。

1

Clazz.method將有一個屬性im_class,它會告訴你的類是什麼。

但是,如果你發現自己想要做到這一點,這可能意味着你正在做的事情的艱辛的道路。我不知道你在做什麼,但是除非你沒有別的選擇,否則這是一種非常糟糕的做法。

0

對於包裝在@classmethod中的方法,該方法將被綁定幷包含指向該類的引用im_self