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”,而不在replace_with_xxx函数中使用“clazz = None”参数???
有没有可能:
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
非常感谢您的阅读。我希望我能说清楚我想要什么。祝你今天过得愉快! :)
最佳答案
我认为这是不可能的,作为一个简单的解释,为什么我们应该考虑以下内容:您可以定义一个函数并将其附加到类,而无需任何额外的声明,并且它将存储为类的字段。并且您可以将相同的函数作为类方法分配给 2 个或更多不同的类。
因此方法不应包含有关该类的任何信息。
关于Python:获取方法所属的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834894/