在模块和类之间选择 [英] choosing between Modules and Classes

查看:50
本文介绍了在模块和类之间选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我必须维护一些全局应用程序状态和全局应用程序范围的方法,例如当前连接的用户,答案总数,创建应用程序配置文件等.有两种选择:

In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:

  1. 使用全局变量制作单独的appstate.py文件,并在其上添加函数.最初看起来不错,但似乎我在代码清晰性方面缺少了一些东西.

在appstate.py文件中创建带有类函数的AppState类,所有其他模块均由其特定作业定义.看起来不错.但是现在我必须写更长的行,如appstate.AppState.get_user_list().而且,这些方法彼此之间并没有太大关系.我可以创建单独的类,但是那样的类太多了.

Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.

如果我使用类,则将使用类方法.我认为没有必要将类实例化为对象.

If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.

推荐答案

第二种方法似乎更好.我只将第一个用于配置文件之类.

The second approach seems better. I'd use the first one only for configuration files or something.

无论如何,为避免此问题,您可以始终:

Anyway, to avoid the problem you could always:

from myapp.appstate import AppState

这样,您就不必再写长行了.

That way you don't have to write the long line anymore.

这篇关于在模块和类之间选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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