类方法的目的是什么? [英] What is the purpose of class methods?

查看:71
本文介绍了类方法的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在自学 Python,我最近的课程是 Python不是 Java,所以我刚刚花了一段时间将我所有的 Class 方法转换为函数.

I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions.

我现在意识到我不需要使用类方法来完成我在 Java 中使用 static 方法所做的事情,但现在我不确定何时使用它们.我能找到的关于 Python 类方法的所有建议都是像我这样的新手应该避开它们的建议,并且在讨论它们时标准文档是最不透明的.

I now realise that I don't need to use Class methods for what I would done with static methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.

有没有人有在 Python 中使用 Class 方法的好例子,或者至少有人可以告诉我什么时候可以明智地使用 Class 方法?

Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?

推荐答案

类方法适用于当您需要具有不特定于任何特定实例但仍以某种方式涉及类的方法时.最有趣的是它们可以被子类覆盖,这在 Java 的静态方法或 Python 的模块级函数中根本不可能实现.

Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions.

如果您有一个 MyClass 类和一个在 MyClass 上运行的模块级函数(工厂、依赖注入存根等),请将其设为 classmethod.然后它将可供子类使用.

If you have a class MyClass, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a classmethod. Then it'll be available to subclasses.

这篇关于类方法的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆