Python中的类是否在不同的文件中? [英] Are classes in Python in different files?

查看:180
本文介绍了Python中的类是否在不同的文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很像Java(或php),我习惯于将类分隔为文件.
在Python中是否也一样?另外,我该如何命名文件?
小写像classname.py还是像ClassName.py一样?
如果要从此类创建对象,或者它在同一项目"(netbeans)中,是否可以从中创建对象,是否需要做一些特殊的事情?

解决方案

在Python中,一个文件称为的时候了. /p>


对于命名约定,您可能需要阅读 PEP 8 ,但简短:

类名

几乎没有例外,类名使用CapWords约定. 内部使用的类还带有一个下划线.

包装和模块名称

模块应使用简短的全小写名称.可以使用下划线 在模块名称中添加(如果它可以提高可读性). Python套件应 也具有短的全小写名称,尽管使用下划线是 灰心丧气.

由于模块名称已映射到文件名,而某些文件系统为 不区分大小写并截断长名称,该模块很重要 名称要选择的简短些-在Unix上不会有问题, 但是将代码传输到较旧的Mac或 Windows版本或DOS.


要实例化一个对象,您必须在文件中导入该类.例如

>>> from mymodule import MyClass
>>> obj = MyClass()

>>> import mymodule
>>> obj = mymodule.MyClass()

>>> from mypackage.mymodule import MyClass
>>> obj = MyClass()


您在问一些基本的知识,所以我建议阅读教程.

Much like Java (or php), I'm use to seperating the classes to files.
Is it the same deal in Python? plus, how should I name the file?
Lowercase like classname.py or the same like ClassName.py?
Do I need to do something special if I want to create an object from this class or does the fact that it's in the same "project" (netbeans) makes it ok to create an object from it?

解决方案

In Python, one file is called a module. A module can consist of multiple classes or functions.

As Python is not an OO language only, it does not make sense do have a rule that says, one file should only contain one class.

One file (module) should contain classes / functions that belong together, i.e. provide similar functionality or depend on each other.
Of course you should not exaggerate this. Readability really suffers if your module consist of too much classes or functions. Then it is probably time to regroup the functionality into different modules and create packages.


For naming conventions, you might want to read PEP 8 but in short:

Class Names

Almost without exception, class names use the CapWords convention. Classes for internal use have a leading underscore in addition.

and

Package and Module Names

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.


To instantiate an object, you have to import the class in your file. E.g

>>> from mymodule import MyClass
>>> obj = MyClass()

or

>>> import mymodule
>>> obj = mymodule.MyClass()

or

>>> from mypackage.mymodule import MyClass
>>> obj = MyClass()


You are asking essential basic stuff, so I recommend to read the tutorial.

这篇关于Python中的类是否在不同的文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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