Python:获取方法所属的类

标签 python class member

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/

相关文章:

python - psycopg2.ProgrammingError : can't adapt type 'DictRow'

Python:需要用额外的 HTML 或数据库结果替换 HTML 模板中一系列不同的子字符串

python从另一个列表中删除列表

ruby - 替换 Ruby 中的 to_s 方法。没有打印出想要的字符串

c++ - 模板类中的 Int 模板成员函数

arrays - const 结构成员的 typedef 中的灵活数组大小

Python:使用 setup.py install (distutil) 时如何强制覆盖文件

javascript - jQuery:隐藏类,以便隐藏该类随后创建的元素

python - 为什么这个类变量在不同的实例中是相同的?

C++成员布局