python 成语库,在Python中,是“来自Module import ClassName”的成语“典型?

Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet would be defined in ToolSet.py.

Within a package, if another module needs to instanciate an object of class ToolSet, I use:

from ToolSet import ToolSet

...

toolSet = ToolSet()

instead of:

import ToolSet

...

toolSet = ToolSet.ToolSet()

I do this to reduce "stutter" (I prefer to have stutter at the top of the file than within my code.)

Is this a correct idiom?

Here is a related question. Within a package, I often have a small number of classes that I would like to expose to the outside world. These I import inside the __init__.py for that package. For example, if ToolSet is in package UI and I want to expose it, I would put the following in UI/__init__.py :

from ToolSet import ToolSet

So that, from an external module I can write

import UI

...

toolSet = UI.ToolSet()

Again, is this pythonic?

解决方案

To answer your first question, that is the idiom I use, and its use is supported by PEP8 the python style guide

it's okay to say this though:

from subprocess import Popen, PIPE

I like it as it reduces typing and makes sure that things go wrong immediately the file is run (say you mis-spelt an import) rather than some time later when a function using the import is run.

Eg suppose the module Thing doesn't have a Thyng member

from Thing import Thyng

Goes wrong immediately you run the .py file, whereas

import Thing

# ...

def fn():

Thing.Thyng()

Doesn't go wrong until you run fn()

As for your second question, I think that is also good practice. It often happens to me when I factor a single large.py into a directory with an __init__.py and implementation files. Importing things into the __init__.py keeps the interface the same. It is common practice in the standard libraries too.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值