gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:57:16 25 4
gpt4 key购买 nike

如果我有以下类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com