首页 > 代码库 > 【python学习笔记】python中的模块,类,函数,对象,实例(与JAVA的比较)
【python学习笔记】python中的模块,类,函数,对象,实例(与JAVA的比较)
在学习JAVA的时候涉及到了类,对象,方法,域等基本概念。类像一个盒子一样包含各种域和访问更改这些域的方法,而对象是类的特例,比如老师和张老师的关系,老师是一个类,而张老师是一个对象。OOP的关键就是类和对象的使用。
在我学习Python的时候,对模块和类的概念与关系不以为意,在开始动手写脚本的时候不知不觉就昏了头,查阅了些许资料,现写一些小小总结。
为了方便叙述,引入zipfile这个模块的描述,代码比较长,但我们只关心其中大致包含了哪些内容:
>>> import zipfile>>> help(zipfile)Help on module zipfile:NAME zipfile - Read and write ZIP files.DESCRIPTION XXX references to utf-8 need further investigation.CLASSES builtins.Exception(builtins.BaseException) BadZipFile LargeZipFile builtins.object ZipFile PyZipFile ZipInfo class BadZipFile(builtins.Exception) | Method resolution order: | BadZipFile | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __delattr__(self, name, /) | Implement delattr(self, name). | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | | __repr__(self, /) | Return repr(self). | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args BadZipfile = class BadZipFile(builtins.Exception) | Method resolution order: | BadZipFile | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __delattr__(self, name, /) | Implement delattr(self, name). | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | | __repr__(self, /) | Return repr(self). | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args class LargeZipFile(builtins.Exception) | Raised when writing a zipfile, the zipfile requires ZIP64 extensions | and those extensions are disabled. | | Method resolution order: | LargeZipFile | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __delattr__(self, name, /) | Implement delattr(self, name). | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | | __repr__(self, /) | Return repr(self). | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args class PyZipFile(ZipFile) | Class to create ZIP archives with Python library files and packages. | | Method resolution order: | PyZipFile | ZipFile | builtins.object | | Methods defined here: | | __init__(self, file, mode=‘r‘, compression=0, allowZip64=True, optimize=-1) | | writepy(self, pathname, basename=‘‘, filterfunc=None) | Add all files from "pathname" to the ZIP archive. | | If pathname is a package directory, search the directory and | all package subdirectories recursively for all *.py and enter | the modules into the archive. If pathname is a plain | directory, listdir *.py and enter all modules. Else, pathname | must be a Python *.py file and the module will be put into the | archive. Added modules are always module.pyo or module.pyc. | This method will compile the module.py into module.pyc if | necessary. | If filterfunc(pathname) is given, it is called with every argument. | When it is False, the file or directory is skipped. | | ---------------------------------------------------------------------- | Methods inherited from ZipFile: | | __del__(self) | Call the "close()" method in case the user forgot. | | __enter__(self) | | __exit__(self, type, value, traceback) | | close(self) | Close the file, and for mode "w" and "a" write the ending | records. | | extract(self, member, path=None, pwd=None) | Extract a member from the archive to the current working directory, | using its full name. Its file information is extracted as accurately | as possible. `member‘ may be a filename or a ZipInfo object. You can | specify a different directory using `path‘. | | extractall(self, path=None, members=None, pwd=None) | Extract all members from the archive to the current working | directory. `path‘ specifies a different directory to extract to. | `members‘ is optional and must be a subset of the list returned | by namelist(). | | getinfo(self, name) | Return the instance of ZipInfo given ‘name‘. | | infolist(self) | Return a list of class ZipInfo instances for files in the | archive. | | namelist(self) | Return a list of file names in the archive. | | open(self, name, mode=‘r‘, pwd=None) | Return file-like object for ‘name‘. | | printdir(self, file=None) | Print a table of contents for the zip file. | | read(self, name, pwd=None) | Return file bytes (as a string) for name. | | setpassword(self, pwd) | Set default password for encrypted files. | | testzip(self) | Read all the files and check the CRC. | | write(self, filename, arcname=None, compress_type=None) | Put the bytes from filename into the archive under the name | arcname. | | writestr(self, zinfo_or_arcname, data, compress_type=None) | Write a file into the archive. The contents is ‘data‘, which | may be either a ‘str‘ or a ‘bytes‘ instance; if it is a ‘str‘, | it is encoded as UTF-8 first. | ‘zinfo_or_arcname‘ is either a ZipInfo instance or | the name of the file in the archive. | | ---------------------------------------------------------------------- | Data descriptors inherited from ZipFile: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | comment | The comment text associated with the ZIP file. | | ---------------------------------------------------------------------- | Data and other attributes inherited from ZipFile: | | fp = None class ZipFile(builtins.object) | Class with methods to open, read, write, close, list zip files. | | z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True) | | file: Either the path to the file, or a file-like object. | If it is a path, the file will be opened and closed by ZipFile. | mode: The mode can be either read "r", write "w" or append "a". | compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib), | ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma). | allowZip64: if True ZipFile will create files with ZIP64 extensions when | needed, otherwise it will raise an exception when this would | be necessary. | | Methods defined here: | | __del__(self) | Call the "close()" method in case the user forgot. | | __enter__(self) | | __exit__(self, type, value, traceback) | | __init__(self, file, mode=‘r‘, compression=0, allowZip64=True) | Open the ZIP file with mode read "r", write "w" or append "a". | | close(self) | Close the file, and for mode "w" and "a" write the ending | records. | | extract(self, member, path=None, pwd=None) | Extract a member from the archive to the current working directory, | using its full name. Its file information is extracted as accurately | as possible. `member‘ may be a filename or a ZipInfo object. You can | specify a different directory using `path‘. | | extractall(self, path=None, members=None, pwd=None) | Extract all members from the archive to the current working | directory. `path‘ specifies a different directory to extract to. | `members‘ is optional and must be a subset of the list returned | by namelist(). | | getinfo(self, name) | Return the instance of ZipInfo given ‘name‘. | | infolist(self) | Return a list of class ZipInfo instances for files in the | archive. | | namelist(self) | Return a list of file names in the archive. | | open(self, name, mode=‘r‘, pwd=None) | Return file-like object for ‘name‘. | | printdir(self, file=None) | Print a table of contents for the zip file. | | read(self, name, pwd=None) | Return file bytes (as a string) for name. | | setpassword(self, pwd) | Set default password for encrypted files. | | testzip(self) | Read all the files and check the CRC. | | write(self, filename, arcname=None, compress_type=None) | Put the bytes from filename into the archive under the name | arcname. | | writestr(self, zinfo_or_arcname, data, compress_type=None) | Write a file into the archive. The contents is ‘data‘, which | may be either a ‘str‘ or a ‘bytes‘ instance; if it is a ‘str‘, | it is encoded as UTF-8 first. | ‘zinfo_or_arcname‘ is either a ZipInfo instance or | the name of the file in the archive. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | comment | The comment text associated with the ZIP file. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | fp = None class ZipInfo(builtins.object) | Class with attributes describing each file in the ZIP archive. | | Methods defined here: | | FileHeader(self, zip64=None) | Return the per-file header as a string. | | __init__(self, filename=‘NoName‘, date_time=(1980, 1, 1, 0, 0, 0)) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | CRC | | comment | | compress_size | | compress_type | | create_system | | create_version | | date_time | | external_attr | | extra | | extract_version | | file_size | | filename | | flag_bits | | header_offset | | internal_attr | | orig_filename | | reserved | | volume error = class BadZipFile(builtins.Exception) | Method resolution order: | BadZipFile | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __delattr__(self, name, /) | Implement delattr(self, name). | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | | __repr__(self, /) | Return repr(self). | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | argsFUNCTIONS is_zipfile(filename) Quickly see if a file is a ZIP file by checking the magic number. The filename argument may be a file or file-like object too.DATA ZIP_BZIP2 = 12 ZIP_DEFLATED = 8 ZIP_LZMA = 14 ZIP_STORED = 0 __all__ = [‘BadZipFile‘, ‘BadZipfile‘, ‘error‘, ‘ZIP_STORED‘, ‘ZIP_DEF...FILE d:\python34\lib\zipfile.py
可以看到,Help on zipfile module列出了zipfile的六个属性:NAME,DESCRIPTION,CLASSES,FUNCTIONS,DATA,FILE。
函数是可以重用的代码,而模块就是可以重用的函数与变量的集合。和JAVA的严谨不一样,你可以往模块中放许多东西,类,定义的函数,甚至独立的域。一个模块对应一个.py文件。每个python程序也是一个模块。JAVA的.java文件是把一个或者多个封装得很好的类放在同一个.java文件中。一个JAVA程序总是在类里找到main入口开始运行。由此看来,.py和.java文件在内容和作用上都有很大差别。从某种意义上来说,.py文件更加像C中的头文件(只是头文件不能运行)。
有意思的是,在python中,一切都是对象,包括函数,数据域,数值等等。所以,模块就是一个盛了很多对象的容器。这个容器被标好标码,你可以通过路径和名字找到它,查阅上面的标码从中拿到你想要的对象,访问、使用或者更改它们。
而类就是小的容器,也是模块的一部分。不同的是,一个类可以衍生出很多很多类。而模块被import之后就只有一个了。
python似乎并不像JAVA一样强调 类和对象的关系,反而强调 对象和对象的关系 以及 对象和实例的关系,这一点让习惯使用JAVA的人有些迷惑。对python而言,“其实都是实例化的”。python的类关系向一棵树,每个叶子之间有两种导航关系:1 子类继承父类;2 子类构建实例。这一点,从type和object的鸡、蛋关系里就能察觉出来。
具体可见《python中的类型关系和继承关系》以及《python类型和对象》:
http://developer.zdnet.com.cn/2008/0521/874673.shtml
http://wenku.baidu.com/link?url=qFUbnlpt_YuQwNdsiLpaDBs10CwX48MyCWwvOUIf3t66LLCDoZk9mnTX1hJm0viY2Q1rlWQb3i4TBdOJ7DnkVQyJKvGAH1Av2NjWUFph7Fm
个人想法,还有许多纰漏,还望大家指正。
【python学习笔记】python中的模块,类,函数,对象,实例(与JAVA的比较)