Skip to main content
 首页 » 编程设计

python之静态方法 : get the class name

2025年05月04日8jillzhang

有没有办法找到静态方法所属的类的名称?

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 个函数来“序列化/反序列化”函数/类方法/静态方法。

这意味着,有人可以将一个函数传递给序列化函数并获取一个字符串。

a_string = serialize(A.my_classmethod) 

例如,这个字符串可以存储在数据库中。 然后,这个字符串应该足以解析能够调用它的函数:

# later on... 
f = deserialize(a_string) 
# I can use my function 
f(...) 

我可以让它为函数或类方法工作,但不能为静态方法工作,因为我无法弄清楚它所属的类并使用 getattr...

请您参考如下方法:

使用“voodoo”你可以解决这个问题,但说真的 - 你只是想绕过数据模型 - 那有什么用呢?如果你想要一个类方法 - 使用类方法。如果它们可以互换,它们就不会有所不同!

还有:

@classmethod 
def my_classmethod(): 
    return 'classmethod' 

应该是:

@classmethod 
def my_classmethod(cls): # assuming no args 
    return cls.__name__ # instead of A.my_classmethod.im_self.__name__