你知道吗↑↑↑ 它没有
假设我有一个带有一些实用方法的类:
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,也许是用一个模块
@classmethod
就是要走的路:关于martijnpieters评论的澄清:我通常避免
@staticmethod
,我更喜欢采用always@classmethod
,因为它允许我引用类及其方法(我不同意关于用函数编写模块的建议…我是OOP的支持者:P)如果您需要对当前类(可以是子类)的引用,那么一定要将其设置为
classmethod
这并不过分;Python绑定类方法的工作量与静态方法或常规方法没有什么不同
但是,除非必须,否则不要在这里使用类。Python不是Java,您没有使用类,函数可以在类之外运行
看起来
Utils
永远不会被子类化或实例化;它只是静态方法的包装器。在这种情况下,这些方法都可以转换为模块级函数,可能在一个单独的utils
模块中:相关问题 更多 >
编程相关推荐