python - 在 python 中调用静态方法而不是类名本身是个好主意吗

标签 python python-2.7 python-3.x

如果我有以下类(class)。

class Foo:
    @staticmethod
    def _bar():
        # do something
        print "static method"

    def instancemethod(self):
        Foo._bar()  # method 1
        self._bar() # method 2

在这种情况下,方法 1 是在 Python 世界中调用 staticmethod _bar() 还是方法 2 的首选方式?

最佳答案

编写表达你想做什么的代码。如果您想在此处调用此方法:

class Foo:
    @staticmethod
    def _bar():  # <-- this one
        # do something
        print "static method"

然后指定特定的方法:

Foo._bar()

如果你想调用任何self._bar解析为,这意味着您实际上已经决定重写它是有意义的,并确保您的代码在该方法被重写时仍然表现合理,然后指定 self._bar :

self._bar()

最有可能的是,此方法并未设计为被覆盖,使用它的代码也未设计为预期会被覆盖,因此您可能需要 Foo._bar() .

关于python - 在 python 中调用静态方法而不是类名本身是个好主意吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37692915/

相关文章:

python - 未更新 GAE 数据存储的索引

python - bash 和 python 管道的区别

python - 具有不同数量的参数 (*args) 和具有默认值的参数的函数?

python - 无法使用参数名称调用具有单个位置参数的 Cythonized 函数

csv - 如何将 zip 文件中的文件读取为文本而不是字节?

Python 意外导入位置

python - 尝试调用类方法时出现 NameError 问题

regex - Django AttributeError 'tuple'对象没有属性 'regex'

python-2.7 - 访问 Theano 共享变量的数据

python - 将命名元组的值从字符串转换为整数