有没有办法找到staticmethod所属类的名称?staticmethod:获取类名?
class A(object):
@staticmethod
def my_staticmethod():
return 'static'
@classmethod
def my_classmethod():
return 'classmethod'
In [2]: A.my_staticmethod
Out[2]: <function utils.my_staticmethod>
In [3]: A.my_classmethod
Out[3]: <bound method type.my_classmethod of <class 'utils.A'>>
In [4]: A.my_classmethod.im_self.__name__
Out[4]: 'A'
对于类方法,我可以通过A.my_classmethod.im_self.__name__
获取类的名字,但我无法弄清楚一个静态方法。
有什么想法? 谢谢。
嗯,实际上这是我正在尝试做的。 我想做2个函数来“序列化/反序列化”一个函数/ classmethod/staticmethod。
这意味着,有人可以将函数传递到序列化函数并获取字符串。
a_string = serialize(A.my_classmethod)
此字符串可以存储在数据库例如.. 然后,该字符串应该足以解决函数可以调用它:
# later on...
f = deserialize(a_string)
# I can use my function
f(...)
我可以使它工作对于一个函数或类方法,但不是静态方法,因为我无法弄清它所属的类,并使用getattr ...
可能重复[在python中如何获取其静态方法中的类的名称](http://stackoverflow.com/questions/4691925/in-python-how-to-get-name-of-a- class-inside-its-static-method) – BrenBarn 2012-07-28 20:51:52
基本上静态方法的要点是它与其类没有关系。如果你想知道它在什么类,不要使用静态方法。 – BrenBarn 2012-07-28 20:52:40
这里也重复:http://stackoverflow.com/questions/949259/how-do-i-infer-the-class-to-which-a-staticmethod-belongs – gnr 2012-07-28 20:55:42