命名空间和类 [英] Namespacing and classes

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

问题描述

我正在尝试用Python编写一些(在我看来)可读的代码.我需要一个包含许多类的模块.从理论上讲,我知道完成此操作所需的一切:我可以简单地将类定义放在单个模块文件中.

I'm trying to write some (in my opinion) readable code in Python. I need a module that will contain a number of classes. Theoretically I know everything that is needed to accomplish this: I can simply put class definitions in a single module file.

出于可读性考虑,我想将每个类定义放入单独的文件中(它们开始变得很冗长!),并将所有这些类放入一个目录中.每当我创建新文件时,尽管它的内容在我需要的位置可见,但内部的类定义受不需要的模块限制.

For readability purposes I want to put every class definition into separate file (they are starting to be quite lengthy!), and all these classes into one directory. Whenever I create new file although it's contents are visible where I need them, class definition that's inside is scoped with unneeded module.

我应该怎么做?这样做的"Python"方式是什么?

How should I do it? What is 'Python' way to do that?

推荐答案

将它们全部导入到__init__.py中,然后让使用者导入程序包.

Import them all within __init__.py, and then have the consumer import the package.

from .module1 import Class1
from .module2 import Class2
 ...

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

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