Python中的静态类 [英] Static classes in Python

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

问题描述

我曾经读过(我认为在微软的一个页面上),当你不需要两个或多个类的实例时,这是一个使用静态类的好方法。

I once read (I think on a page from Microsoft) that it's a good way to use static classes, when you don't NEED two or more instances of a class.

我在使用Python编写程序。如果对于类的每个方法使用 @classmethod ,这是一个坏的风格吗?

I'm writing a program in Python. Is it a bad style, if I use @classmethod for every method of a class?

推荐答案

在我的经验中,创建类是一个很好的解决方案,有很多原因。一个是你使用类作为一个正常类(特别是使得不只是一个实例)更频繁地超过你可能认为。这也是一个合理的风格选择坚持类的一切;这可以使读者/维护你的代码,esp如果他们是非常OO - 他们会很舒服的类,更容易。正如其他回复中所指出的,仅仅使用裸函数来实现也是合理的。你可能希望从一个类开始,使它成为一个单例/ Borg模式(很多例子,如果你googlefor这些);它给你灵活性(重用)类来满足其他需求。我建议反对'静态类'的方法是非常规和非Pythonic,这使它更难阅读和维护。

In my experience creating a class is a very good solution for a number of reasons. One is that you wind up using the class as a 'normal' class (esp. making more than just one instance) more often than you might think. It's also a reasonable style choice to stick with classes for everthing; this can make it easier for others who read/maintain your code, esp if they are very OO - they will be comfortable with classes. As noted in other replies, it's also reasonable to just use 'bare' functions for the implementation. You may wish to start with a class and make it a singleton/Borg pattern (lots of examples if you googlefor these); it gives you the flexibility to (re)use the class to meet other needs. I would recommend against the 'static class' approach as being non-conventional and non-Pythonic, which makes it harder to read and maintain.

这篇关于Python中的静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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