class myClass(object):
def __init__(self):
print self.__class__.__name__
myClass()
можно ли узнать имя текущего метода? (т.е. получить “__init__” или другое название)
class myClass(object):
def __init__(self):
print self.__class__.__name__
myClass()
>>> def get_called_name(depth=0):
... return sys._getframe(depth + 1).f_code.co_name
...
>>> class Hello:
... def __init__(self):
... print get_called_name()
...
>>> h = Hello()
__init__
>>>
>>> class A(object):
... pass
...
>>> def f(self):
... return sys._getframe().f_code.co_name
...
>>> A.g = f
>>> a = A()
>>> a.g()
'f'
from new import function, instancemethod
from byteplay import Code, LOAD_CONST, STORE_FAST
from types import MethodType
class A(object):
def __getattribute__(self, name):
attr = super(A, self).__getattribute__(name)
if type(attr) is MethodType and not hasattr(attr.im_func, '_patched'):
c = Code.from_code(attr.func_code)
c.code[0:0] = [
(LOAD_CONST, name),
(STORE_FAST, '_func_name')]
f = function(c.to_code(), globals(), attr.__name__)
f._patched = True
attr = instancemethod(f, self, A)
setattr(self, name, attr)
return attr
def zzz(self):
print locals().get('_func_name')
def f(self):
print locals().get('_func_name')
A.g = f
a = A()
a.zzz()
a.zzz()
a.g()