静态方法中的类引用

2024-10-02 18:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

你知道吗↑↑↑ 它没有

假设我有一个带有一些实用方法的类:

class Utils:
    @staticmethod
    def do_stuff():
        # some stuff
        Utils.do_other_stuff()
        # some more stuff

    @staticmethod
    def do_other_stuff():
        # somehting other

我不太喜欢Utils.do_other_stuff()部分

如果它是实例方法,我将通过self引用它,但这里我必须编写完整的类名

在这里使用@classmethod是个好主意,还是杀伤力过大或者有没有更干净的方法来编写util,也许是用一个模块


Tags: 实例方法selfdefmoreutilssomedo
3条回答

@classmethod就是要走的路:

class Utils:
    @classmethod
    def do_stuff(cls):
        # some stuff
        cls.do_other_stuff()
        # some more stuff

    @classmethod
    def do_other_stuff(cls):
        # somehting other

关于martijnpieters评论的澄清:我通常避免@staticmethod,我更喜欢采用always@classmethod,因为它允许我引用类及其方法(我不同意关于用函数编写模块的建议…我是OOP的支持者:P)

如果您需要对当前类(可以是子类)的引用,那么一定要将其设置为classmethod

这并不过分;Python绑定类方法的工作量与静态方法或常规方法没有什么不同

但是,除非必须,否则不要在这里使用类。Python不是Java,您没有使用类,函数可以在类之外运行

看起来Utils永远不会被子类化或实例化;它只是静态方法的包装器。在这种情况下,这些方法都可以转换为模块级函数,可能在一个单独的utils模块中:

# No class!
def do_stuff():
    ...
    do_other_stuff()
    ...

def do_other_stuff():
    ...

相关问题 更多 >