python - 静态方法 : get the class name?

标签 python

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

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__

关于python - 静态方法 : get the class name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11704534/

相关文章:

python - 将数据帧重复合并到数据帧的单列中的优雅而有效的方法

python - 列表索引超出范围?

python - AWS SAM : Unable to unmarshal input

python - 谷歌 foobar gearing_up_for_destruction

python - Tensorflow 填充实现

python - 如何从github python安装 "sparse_dot_topn"

python - 尝试使用tensorfow_to_barracuda.py 将.pb 转换为.nn 时出现问题

python - SQLAlchemy 中所有行的高效更新

python - 创建不会与其他系统冲突的 UUID

python - 合并 Pandas Dataframe 中不同类型的列