This article illustrates the Python object and object-oriented technology. Share to everyone for your reference, specific as follows:
1 See one 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 to parsing its files appropriately;
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, Stripnulls), "Artist": (33, 63, Stripnulls), "album": (Stripnulls), "Year": (Stripnulls), "comment": ( 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) TAGD ATA = fsock.read (128) Finally:fsock.close () if tagdata[:3] = = "Tag": For TAG, (Start, End, PA
Rsefunc) 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, k
EY, 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) to F in Fil Elist] 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 importing modules using from module import
The import module we used to learn is the following syntax:
Import Module Name
So when you need to use something in that module. To pass the form of module name. XXX. For example:
>>> Import Types
>>> types. Functiontype
<type ' function ' >
>>> functiontype
An error occurs if you use the name directly without the module name. So print:
Traceback (most recent):
File "<interactive input>", line 1, in <module>
nameerror:name ' Fu Nctiontype ' is not defined
Now look at another syntax for importing names in a module:
From Module name Import name
or use
From Module name Import *
For example:
>>> from types Import Functiontype
The imported name can be used directly without the module name. Such as:
>>> functiontype
<type ' function ' >
3 Definition of Class
To define the syntax for a class:
Class Name:
Pass
Or
Class name (base class list):
Pass
Pass is the key word for Python. It means doing nothing.
Class can also have class documents. If any. He should be the first thing in the definition of a class. Such as:
Class A (B):
"This is Class A."
The constructor of the class is:
But. That's exactly right. This can only be done after you create the class object. The method that is automatically executed. 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)
This defines a construction method for Class A. And in which the constructor method of base class B is invoked.
It is to be noted that. In Python. When you construct a derived class. The constructor method of the base class is not called automatically. You must write it explicitly if you need it.
All the class methods. The first parameter is used to receive the this pointer. The name of the custom parameter is self.
Do not pass this argument when called. It will automatically be added.
But in a constructor like the top. When calling the __init () of the base class. This parameter must be explicitly given.
4 Instantiation of Class
Instantiating a class is similar to other languages. Just take its class name as a function call on the line. And there's no other language like new.
Class name (parameter table)
The parameter table does not have to give the first argument of __init__ self.
For example:
A = A ()
We can view the document for that class through an instance of the class or class. This is through their __doc__ properties. Such as:
>>> a.__doc__
' This are Class A. '
>>> a.__doc__
' This is Class A. '
We can also get its class from an instance of a class. This is through its __class__ property. Such as:
>>> a.__class__
<class __main__. A at 0x011394b0>
After an instance of the class is created. We don't have to worry about the recycling problem. Garbage collection automatically destroys unused objects based on reference counts.
In Python. The data members of the class do not have a specific declaration statement. It's "sudden" when you assign a value. For example:
Class A:
def __init__ (self):
self.data = []
Then. Automatically let data be a member of Class A.
is then within the definition of the class. To use a member variable or member method in a class. be qualified with the self name.
Therefore, it is generally needed to generate data members. Assign a value to the self. Member name in any method.
But. All data properties are assigned an initial value in the __init__ method. is a good habit.
Python does not support function overloading.
Here again the code indent. As a matter of fact. If a block of code is only one sentence. Can be placed directly behind the colon. You do not need to wrap the line indent format.
6 Private class method
Different from the ordinary method. After you define a private method in the class. You don't have to call them explicitly. But at some point Python is automatically invoked.
Gets and sets the data item.
This requires defining the __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]
Here the a[1] calls the __getitem__ method. It equals a.__getitem__ (1)
Similar to the __getitem__ method, there are __setitem__
For example, in Class A above, define:
def __setitem__ (self, Key, item):
Self.li[key] = Item
Then call this method as follows:
A[1] = 0 it equals call a.__setitem__ (1, 0)
7 Advanced Proprietary class methods
Similar to the __getitem__ __setitem__. There are also special specialized functions. As follows:
def __repr__ (self): return repr (Self.li)
This private method is used for string representations of this object. Call it through the built-in function repr (). Such as
This repr () can function on any object.
As a matter of fact. In the interactive window. Just enter the variable name. The value of the variable is displayed with repr.
def __cmp__ (self, x):
if Isinstance (x, A): Return cmp (Self.li, X.li)
It is used to compare two instances of self and X for equality. It is called as follows:
A = a ()
B = A ()
a = = b
This compares the equality of A and B. The same as calling a.cmp (b)
def __len__ (self): return len (self.li)
It is used to return the length of the object. It is invoked when Len (object) is used.
Use it to specify a logical length value that you want.
def __delitem__ (self, key): Del Self.li[key]
This function is called when the Del Object [key] is called.
8 Class Properties
A class attribute refers to something like a static member of C + +.
You can also have class attributes in Python. For example:
can be referenced (modified) by a class. Or it can be referenced (modified) by an instance. Such as:
Or
9 Private functions
Python also has the concept of "private":
Private functions cannot be invoked from outside their modules.
Private class methods cannot be invoked from outside their classes.
Private properties cannot be accessed from outside their classes.
There are only two types of Python, private and public. There is no concept of protection. To distinguish between public and private is to see the function. Class method. The name of the Class property.
The name of the private thing begins with __. (A proprietary method, such as __getitem__, is not private, for example).
For more information on Python-related content readers can view the site: "The Python object-oriented Programming Introduction and Advanced Tutorial", "Python file and directory operation tips Summary", "Python Picture Operation skills Summary", "Python data structure and Algorithms tutorial", " Python socket Programming Tips Summary, "Python function usage Tips", "python string manipulation Tips", "Python Code Operation tips Summary" and "The Python Introductory and advanced Classic course"
I hope this article will help you with Python programming.