gpt4 book ai didi

python - 在 Python 的类中访问静态方法的惯用方法

转载 作者:行者123 更新时间:2023-11-28 22:49:06 24 4
gpt4 key购买 nike

我明白 staticmethod 应该始终由它们所属的类名引用。但我看到它们也可以通过关键字 self 访问。

这有点令人困惑,我没有看到解释器抛出错误。

import unittest

class TestA(unittest.TestCase):
@staticmethod
def fun1():
return True

@staticmethod
def fun2():
return False

def test_one(self):
assert TestA.fun1() == True

def test_two(self):
assert self.fun2() == False

if __name__ == '__main__':
unittest.main()

访问静态方法的正确方法是什么。像上面的 TestA.fun1 对我来说很清楚,或者像 self.fun2 有点担心,因为没有实例发送到 fun2。

最佳答案

the documentation 中所述,任何一种方式都可以接受:

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

从某种意义上说,staticmethod 的意义在于允许您调用该方法而不必担心您是在实例还是类上调用它。

关于python - 在 Python 的类中访问静态方法的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24334739/

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