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
非常感謝您的閱讀。我希望我能說清楚一點,我想要什麼。祝你今天愉快! :)
多麼可怕的想法。你爲什麼試圖修改一個類的結構?爲什麼不定義一個新班級?爲什麼不使用像** Strategy **這樣更簡單的設計模式? – 2011-01-29 03:56:38