开发者

Python: Get the class, which a method belongs to

开发者 https://www.devze.com 2023-02-07 03:36 出处:网络
Do python class-methods have a method/member themselves, which indicates the class, they belong to? For example ...:

Do python class-methods have a method/member themselves, which indicates the class, they belong to?

For example ...:

# 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!

Now my question is: How is it possible, to get all method/function calls print "xxx", WITHOUT the "clazz = None" argument in the replace_with_xxx function???

Is there something possible like:

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

Thank you very much for reading. I hope, i could make it a little bit clear, what开发者_如何学JAVA i want. Have a nice day! :)


I do not think this is possible and as a simple explanation why we should think about following: you can define a function and attach it to the class without any additional declarations and it will be stored as a field of the class. And you can assign the same function as a class method to 2 or more different classes.

So methods shouldn't contain any information about the class.


Clazz.method will have an attribute im_class, which will tell you what the class is.

However, if you find yourself wanting to do this, it probably means you are doing something the hard way. I don't know what you are trying to accomplish but this is a really bad way to do just about anything unless you have no other option.


For methods wrapped in @classmethod, the method will be bound and contain the reference im_self pointing to the class.

0

精彩评论

暂无评论...
验证码 换一张
取 消