Detailed explanation of python objects and object-oriented technology

WBOY
Release: 2016-08-04 08:55:37
Original
1451 people have browsed it

The examples in this article describe python objects and object-oriented technology. Share it with everyone for your reference, the details are as follows:

1 Let’s look at an example first. This chapter will explain this example program:

File: fileinfo.py:

"""Framework for getting filetype-specific metadata.
Instantiate appropriate class with filename. Returned object acts like a
dictionary, with key-value pairs for each piece of metadata.
  import fileinfo
  info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
  print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
Or use listDirectory function to get info on all files in a directory.
  for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
    ...
Framework can be extended by adding classes for particular file types, e.g.
HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for
parsing its files appropriately; see MP3FileInfo for example.
"""
import os
import sys
from UserDict import UserDict
def stripnulls(data):
  "strip whitespace and nulls"
  return data.replace("{post.content}", "").strip()
class FileInfo(UserDict):
  "store file metadata"
  def __init__(self, filename=None):
    UserDict.__init__(self)
    self["name"] = filename
class MP3FileInfo(FileInfo):
  "store ID3v1.0 MP3 tags"
  tagDataMap = {"title"  : ( 3, 33, stripnulls),
         "artist" : ( 33, 63, stripnulls),
         "album"  : ( 63, 93, stripnulls),
         "year"  : ( 93, 97, stripnulls),
         "comment" : ( 97, 126, stripnulls),
         "genre"  : (127, 128, ord)}
  def __parse(self, filename):
    "parse ID3v1.0 tags from MP3 file"
    self.clear()
    try:
      fsock = open(filename, "rb", 0)
      try:
        fsock.seek(-128, 2)
        tagdata = fsock.read(128)
      finally:
        fsock.close()
      if tagdata[:3] == "TAG":
        for tag, (start, end, parseFunc) in self.tagDataMap.items():
          self[tag] = parseFunc(tagdata[start:end])
    except IOError:
      pass
  def __setitem__(self, key, item):
    if key == "name" and item:
      self.__parse(item)
    FileInfo.__setitem__(self, key, item)
def listDirectory(directory, fileExtList):
  "get list of file info objects for files of particular extensions"
  fileList = [os.path.normcase(f)
        for f in os.listdir(directory)]
  fileList = [os.path.join(directory, f)
        for f in fileList
        if os.path.splitext(f)[1] in fileExtList]
  def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
    "get file info class from filename extension"
    subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
    return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
  return [getFileInfoClass(f)(f) for f in fileList]
if __name__ == "__main__":
  for info in listDirectory("/music/_singles/", [".mp3"]):
    print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
    print

Copy after login

2 Use from module import to import the module

The import module we learned before uses the following syntax:

import module name

In this way, when you need to use things in this module, you must use the form of module name.XXX. For example:

>>> import types
>>> types.FunctionType
<type 'function'>
>>> FunctionType

Copy after login

If you do not use the module name but directly use the name, it will be an error. So print:

Traceback (most recent call last):
 File "<interactive input>", line 1, in <module>
NameError: name 'FunctionType' is not defined

Copy after login

Now look at another syntax for importing names in modules:

from module name import name

or use

from module name import *

For example:

>>> from types import FunctionType

Copy after login

In this way, the imported name can be used directly without passing the module name. For example:

>>> FunctionType
<type 'function'>

Copy after login

3 Class definition

Syntax for defining classes:

class class name:
Pass

or

class class name (base class list):
Pass

The pass is a keyword of Python. It means do nothing.

A class can also have a class document. If so, it should be the first thing in the class definition. For example:

class A(B) :
  " this is class A. "

Copy after login

The constructor of the

class is:

__init__

Copy after login

However, to be precise, this can only be regarded as a method that is automatically executed after creating an object of this type. When this function is executed, the object has been initialized.

For example:

class A(B) :
  "this is class A. "
  def __init__ (self):
    B.__init__(self)

Copy after login

A constructor is defined here for class A. And the constructor of base class B is called in it.

It should be noted that in Python, when constructing a derived class, the constructor of the base class will not be "automatically" called. If necessary, it must be written explicitly.

All class methods. The first parameter is used to receive this pointer. The customary name of this parameter is self.

Do not pass this parameter when calling. It will be added automatically.

But in the constructor like above, when calling __init() of the base class, this parameter must be given explicitly.

4 Instantiation of classes

Instantiating a class is similar to other languages. Just use its class name as a function call. There is no new or the like in other languages.

Class name (parameter list)

The first parameter self.

of __init__ does not need to be given in the parameter list.

For example:

a = A()

We can view the documentation for a class or an instance of a class. This is through their __doc__ attribute. For example:

>>> A.__doc__
'this is class A. '
>>> a.__doc__
'this is class A. '

Copy after login

We can also get its class through its instance. This is through its __class__ attribute. For example:

>>> a.__class__
<class __main__.A at 0x011394B0>

Copy after login

After creating an instance of the class, we don’t have to worry about recycling. Garbage collection will automatically destroy unused objects based on reference counting.

In Python, there are no special declaration statements for class data members. Instead, they are "suddenly generated" during assignment. For example:

class A :
  def __init__(self) :
    self.data = []

Copy after login

At this time, data is automatically made a member of class A.

Afterwards, within the definition of the class. If you want to use member variables or member methods in the class, you must use self.name to qualify.

So data members are generally generated. Just assign a value to self.member name in any method.

However, it is a good habit to assign an initial value to all data attributes in the __init__ method.

Python does not support function overloading.

Let’s talk about code indentation here. In fact, if a code block has only one sentence, it can be placed directly after the colon without the need for line breaks and indentation format.

6 Special class methods

Different from ordinary methods. After defining special methods in a class, you are not required to call them explicitly. Instead, Python will automatically call them at certain times.

Get and set data items.

This requires defining __getitem__ and __setitem__ methods in the class.

For example:

>>> class A:
... def __init__(self):
...  self.li = range(5)
... def __getitem__(self, i):
...  return self.li[-i]
...
>>> a = A()
>>> print a[1]

Copy after login

a[1] here calls the __getitem__ method. It is equal to a.__getitem__(1)

Similar to the __getitem__ method is __setitem__

For example, defined in class A above:

def __setitem__(self, key, item):
  self.li[key] = item

Copy after login

Then call this method as follows:

a[1] = 0 which is equivalent to calling a.__setitem__(1, 0)

7 Advanced special class methods

Similar to __getitem__ __setitem__. There are also some special dedicated functions. As follows:

def __repr__(self): return repr(self.li)

Copy after login

This special method is used to represent the string representation of this object. It is called through the built-in function repr(). Such as

repr(a)

Copy after login

This repr() can be applied to any object.

Actually, in the interactive window, just enter the variable name and press Enter. Repr will be used to display the value of the variable.

def __cmp__(self, x):
  if isinstance(x, A): return cmp(self.li, x.li)

Copy after login

It is used to compare whether two instances self and x are equal. It is called as follows:

a = A()
b = A()
a == b

Copy after login

这里比较 a和b是否相等. 和调用 a.cmp(b) 一样

def __len__(self): return len(self.li)

Copy after login

它用来返回对象的长度. 在使用 len(对象) 的时候会调用它.
用它可以指定一个你希望的逻辑长度值.

def __delitem__(self, key): del self.li[key]

Copy after login

在调用 del 对象[key] 时会调用这个函数.

8 类属性

类属性指的是象c++中静态成员一类的东西.

Python中也可以有类属性. 例如:

class A :
  l = [1, 2, 3]

Copy after login

可以通过类来引用(修改). 或者通过实例来引用(修改). 如:

A.l

Copy after login

a.__class__.l

Copy after login

9 私有函数

Python中也有"私有"这个概念:

私有函数不可以从它们的模块外边被调用.
私有类方法不能从它们的类外边被调用.
私有属性不能从它们的类外边被访问.

Python中只有私有和公有两种. 没有保护的概念. 而区分公有还是私有是看函数. 类方法. 类属性的名字.

私有的东西的名字以 __ 开始. (但前边说的专用方法(如__getitem__)不是私有的).

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python文件与目录操作技巧汇总》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!