Python模块初始化 [英] Python Module Initialization

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

问题描述

在模块代码中初始化模块中的对象是否是错误的做法?

Is it bad practice to initialize the objects in the module, in the module code?

Module.py中:

class _Foo(object):
    def __init__(self):
        self.x = 'Foo'

Foo = _Foo()

比起用户代码,您可以:

Than in user code, you could:

>>> from Module import Foo
>>> print Foo.x
'Foo'
>>>

...无需在用户代码中初始化Foo类.当然,仅在不需要参数来初始化对象的情况下有用.

...without having to initialize the Foo class in the user code. Of course, only useful if you don't need arguments to initialize the object.

有没有理由不这样做吗?

Is there a reason not to do this?

推荐答案

通常,您只需要运行使模块可用所需的最低限度的代码.这将对性能(加载时间)产生整体影响,并使调试更加容易.
而且,通常从任何给定的类创建一个以上的实例.

Typically, you only want to run the minimum necessary to have your module usable. This will have an overall effect on performance (loading time), and can also make debugging easier.
Also, usually more than one instance will be created from any given class.

话虽如此,如果您有充分的理由(例如只需要一个类的实例),则一定要在加载时对其进行初始化.

Having said that, if you have good reasons (such as only wanting one instance of a class), then certainly initialize it at load time.

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

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