<分区>
我有一个所有方法都是静态的 python 类,
class SomeClass:
@staticmethod
def somemethod(...):
pass
@staticmethod
def somemethod2(...):
pass
@staticmethod
def somemethod3(...):
pass
这样做正确吗?
标签 python python-3.x
<分区>
我有一个所有方法都是静态的 python 类,
class SomeClass:
@staticmethod
def somemethod(...):
pass
@staticmethod
def somemethod2(...):
pass
@staticmethod
def somemethod3(...):
pass
这样做正确吗?
最佳答案
如果所有方法都是静态的,则不需要类。
(如果您有一个只有 init 和 1 个方法的类,则相同)
class SomeClass:
@staticmethod
def somemethod(...):
pass
@staticmethod
def somemethod2(...):
pass
@staticmethod
def somemethod3(...):
pass
然后你主要像这样使用它:
from someclass import SomeClass
some_class = SomeClass()
some_class.somemethod()
....
def somemethod(...):
pass
def somemethod2(...):
pass
def somemethod3(...):
pass
然后我这样使用它:
import someclass
someclass.somemethod()
...
这不是更干净、更简单吗?
class SomeClass:
foo = 1
def __init__(self, bar):
self.bar = bar
self.foo = 2
@staticmethod
def somemethod():
# no access to self nor cls but can read foo via SomeClass.foo (1)
foo = SomeClass.foo
SomeClass.someclassmethod()
...
@classmethod
def someclassmethod(cls, ...):
# access to cls, cls.foo (always 1), no access to bar
foo = cls.foo
...
def someinstancemethod(self, ...):
# access to self, self.bar, self.foo (2 instead of 1 because of init)
foo = self.foo
bar = self.bar
self.somemethod()
self.someclassmethod()
...
关于python - 具有所有静态方法的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42757961/
相关文章:
python - 如何使用 Streamlit 单击按钮切换页面?
python - PyQt4 和 Python 3 - 显示来自 URL 的图像
python - 使用 python 3.0 的 Numpy
python - 当异常在实际的 'continue' 语句中时,你如何 'for'?
python-3.x - 如何使用 GPU 中的 panda dataframe 读取 csv 文件?
python - 深度学习模型训练速度非常慢 Jetson Nano
python - 使用 Python Paramiko 的嵌套 SSH
python - Bash 或 GoogleCL : new line in a string parameter