Python每个模块和包一个类 [英] Python one class per module and packages

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

问题描述

我正在尝试用Python构建应用程序.从C#/Java背景回来,我喜欢每个文件一个类的方法.我希望我的项目树看起来像这样:

I'm trying to structure my app in Python. Coming back from C#/Java background, I like the approach of one class per file. I'd like my project tree to look like this:

[Service]
    [Database]
        DbClass1.py
        DbClass2.py
    [Model]
        DbModel1.py
        DbModel2.py
    TheService.py
[ServiceTests]
    [Database]
        DbClass1Tests.py
        DbClass2Tests.py
    [Model]
        DbModel1Tests.py
        DbModel2Tests.py
    TheServiceTests.py

  1. 在Python中每个文件一个类可以吗?
  2. 是否可以以这样的方式创建包/模块,以使包像Java的包或.NET的命名空间一样工作,即在DbModel1Tests.py中:

  1. Is the one class per file approach OK in Python?
  2. Is it possible to create packages/modules in such a way so that packages work like Java's packages or .NET's namespaces, i.e. in DbModel1Tests.py:

import Service.Model

def test():
   m = DbModel1()

推荐答案

在我看来,对于1:我不明白为什么不这样做.我认为,不管使用哪种语言,这都是一个好主意,因为当您知道文件中只有一个类时,它可以为您提供文件内容的快速概览.虽然我会为助手类做一个小小的例外,但是由于Python允许嵌套类,所以也可以做得很好.

In my opinion, for 1: I don't see why not. I think, regardless of language this is a good idea as it provides you with a quick overview of what is to be found in a file when you know there will be only a single class in it. I would make a small exception for helper classes though, but as Python allows nested classes this can also be done quite nicely.

对于2:也是可能的.不过,在您的示例中,您可以简单地加载模块,从而使完整的名称空间可以使用其类和功能.

For 2: possible as well. In your example though, you simple load the module, thereby making its classes and functions available by the full namespace.

因此,如果您说import Service.Model,则只能使用m = Service.Model.DBModel1()访问该类.

So, if you say import Service.Model, you can only access the class by using m = Service.Model.DBModel1().

要将事物导入当前名称空间,请执行from Service.Model import *(如果只需要该类,则执行from Service.Model import DBModel1).然后,您可以按照当前的操作进行操作:m = DBModel1().

To import things into the current namespace, do a from Service.Model import * (or from Service.Model import DBModel1 if you only need that class). Then you can do as you currently do: m = DBModel1().

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

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