避免 Python 中的冗余
我最近开始在 Ubuntu Server 管理中使用 Python 2.6,有两个关于冗余的小问题:
第一件事是导入:它们看起来都像
import Class from Class
from class import Class
第二件事是 __init__methods:
__init__(self,arg1,...,argn):
self.arg1 = arg1
...
self.argn = argn
有没有办法避免这些重复?
I recently started using Python 2.6 for Ubuntu Server admin and have two minor issues concerning redundancy:
First thing are imports: They all look something like
import Class from Class
from class import Class
And the second thing are __init__
methods:
__init__(self,arg1,...,argn):
self.arg1 = arg1
...
self.argn = argn
Are there ways to avoid these duplications?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第二件事不是冗余——它是设置实例属性。您也可以这样做:
但是您需要像这样调用 Foo:
另外您的导入似乎有不正确的语法。它应该是
from Class import Class
。这对您来说看起来是多余的,因为您似乎将每个类存储在单独的文件(模块)中 - 这完全是多余的。 Python 不是 Java,您通常应该在一个模块中保存更多对象。请记住,该模块本身就是一个对象。此外,您还应该正确命名模块 - 默认代码样式指南表示模块应该全部小写,没有特殊字符。例如re
或urllib
。The second thing is not redundancy - it is setting instance attributes. You can do it also like this:
But then you need to call Foo like this:
Also your import seems to have improper syntax. It should be
from Class import Class
. This looks redundant to you, because it seems, that you are storing each class in a separate file (module) - and that is exactly redundant. Python is not Java, you should usually hold more objects in one module. Keep in mind, that module itself is an object. Also you should name modules properly - the default code style guide says that modules should be all lowercase with no special chars. Likere
orurllib
for example.类名与其包含模块的名称不同是很常见的。如果每个模块只有一个具有相同名称的类,请考虑将该类在层次结构中向上移动一个级别。
这看起来确实有点烦人,但与其他选择相比,从可读性角度来看,它确实不错。但是,如果您有很多参数只是作为属性分配,而在 init 中没有其他工作,那么请考虑从命名元组或类似的继承,它可以为您生成这样的样板文件。 (Namedtuple 尤其具有其他影响,并且仅有时适用。我将它用作可以处理此类样板文件的基类的示例。)
It is common for class names to be different from their containing module's name. If you have just one class per module with an identical name, consider moving that class up a level in your hierarchy.
This does often seem to be kinda annoying, but it's really not bad, readability-wise, compared to alternatives. However, if you have a lot of parameters that you merely assign as attributes with no other work in your init, then consider inheriting from a namedtuple or similar, which can generate such boilerplate for you. (Namedtuple in particular has other ramifications and will only be sometimes suitable. I'm using it as an example of a base class which can handle this type of boilerplate.)
参数版本:
Version for args: