Home  >  Article  >  Backend Development  >  python objects and object-oriented technology

python objects and object-oriented technology

高洛峰
高洛峰Original
2017-02-28 16:22:501038browse

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

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 module name. It's an error to use the name in it. So print:

>>> import types
>>> types.FunctionType
<type &#39;function&#39;>
>>> FunctionType

Now look at another syntax for importing names in modules:

from module Name import name

or use

from module name import *

For example:

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

This way The imported name can be used directly without the module name. For example:

>>> from types import FunctionType

3 Class definition

The syntax for defining a class:

class class name:

pass

or

class class name (base class list):

pass

where pass is Python keyword. It means doing nothing.

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


>>> FunctionType
<type &#39;function&#39;>

The constructor of the class is:

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

However, to be precise, this can only be regarded as creating an object of this class. After. Automatically executed method. When this function is executed, the object has been initialized.

For example:

__init__

Here is the definition of class A A constructor is created, 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. It is customary to name this parameter self.

Do not use it when calling Pass this parameter. 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 a class

Instantiating a class is similar to other languages. Just call its class name as a function. 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 table. 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:

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

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

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

After creating an instance of the class. We don’t need to Worry about recycling. Garbage collection will automatically destroy unused objects based on reference counts.

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

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

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

After that, in the definition of the class, you need to use the class The member variables or member methods in must be qualified by the self. name.

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

But . 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. No newline and indentation format is required.

6 Special class methods

are different from ordinary methods. Define special methods in the class After the method. You do not need to call them explicitly. Instead, Python automatically calls them at certain times.

Get and set data items.

This requires defining __getitem__ and __setitem__ method.

For example:

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

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:

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

Then call this method as follows:

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

7 Advanced special class method

and_ _getitem__ __setitem__ is similar. There are also some special dedicated functions. As follows:

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

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

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

This repr() can act on any object.

In fact. In the interactive window. Just enter the variable name and press Enter. Use repr to display the value of the variable.

repr(a)

It is used to compare whether two instances self and x are equal. When calling it As follows:

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

This compares whether a and b are equal. It is the same as calling a.cmp(b)

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

It is used to return the length of the object. It will be called when using len (object).

Use it to specify a logical length value you want.

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


This function will be called when calling del object [key].

8 Class attribute

Class attribute refers to a static member like in c++ Class things.

There can also be class attributes in Python. For example:

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

can be referenced (modified) through the class. Or through Instance to reference (modify). For example:

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

or

A.l

9 Private function

There is also the concept of "private" in Python:

Private functions cannot be called from outside their modules.
Private class methods cannot be called from outside their classes.
Private attributes They cannot be accessed from outside their classes.

There are only two types of private and public in Python. There is no concept of protection. The distinction between public and private depends on functions, class methods, and class attribute names.

The names of private things start with __. (But the special methods mentioned earlier (such as __getitem__) are not private).

For more articles related to python objects and object-oriented technology, please pay attention to the PHP Chinese website !

Statement:
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