This article mainly introduces python objects and object-oriented technology, and analyzes in detail the concepts and usage skills of classes, objects, methods, and attributes related to Python objects in the form of examples, for more information about python objects and object-oriented technology, see the following example. We will share this with you for your reference. The details are as follows:
1. let's look at an example.. This chapter will explain the example program:
File: fileinfo. py:
"""Framework for getting filetype-specific metadata.Instantiate appropriate class with filename. Returned object acts like adictionary, 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 forparsing its files appropriately; see MP3FileInfo for example."""import osimport sysfrom UserDict import UserDictdef 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"] = filenameclass 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 the from module import module
The import module we learned previously uses the following syntax:
Import module name
In this way, when you need to use something in this module, the module name should be in the form of. XXX. for example:
>>> import types>>> types.FunctionType
>>> FunctionType
If you directly use the module name without using it, an error occurs. Therefore, print:
Traceback (most recent call last): File "
", line 1, in
NameError: name 'FunctionType' is not defined
Now let's look at the syntax of the name in another import module:
From module name import name
Or use
From module name import *
For example:
>>> from types import FunctionType
In this way, the imported name can be directly used without passing the module name. for example:
>>> FunctionType
Class 3 definition
Syntax of the definition class:
Class name:
Pass
Or
Class name (base class list ):
Pass
The pass is the keyword of Python, indicating that nothing is done.
The 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. "
Class constructor:
__init__
However, to be accurate, this is only a method automatically executed after the class object is created. 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)
A constructor is defined for Class A and the constructor of class B is called.
Note that when constructing a derived class in Python, the base class constructor is not called Automatically. if necessary, it must be explicitly written out.
All class methods. The first parameter is used to receive the this pointer. the name of this parameter is self.
Do not pass this parameter during the call. it will be automatically added.
However, in the above constructor, when _ init () of the base class is called, this parameter must be explicitly given.
Class 4 instantiation
Instantiating a class is similar to other languages. Just think of its class name as a function call. there is no new in other languages.
Class name (parameter table)
The first parameter self of _ init _ is not required in the parameter table.
For example:
A = ()
We can view the documents of the class through the class or class instance. this is done through their _ doc _ attributes. for example:
>>> A.__doc__'this is class A. '>>> a.__doc__'this is class A. '
We can also get its class through the class instance. this is through its _ class _ attribute. for example:
>>> a.__class__
After a class instance is created, we do not have to worry about collection. garbage collection will automatically destroy unnecessary objects based on the reference count.
In Python, the data members of the. class do not have specific declaration statements, but "suddenly generate" when assigning values. for example:
class A : def __init__(self) : self.data = []
In this case, data is automatically used as A member of Class.
In the class definition, to use the member variables or member methods in the class, use the self. name to limit.
Therefore, data members are usually generated. you can assign values to the self. member names 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.
Here we will talk about code indentation. In fact, if a code block contains only one sentence, it can be placed directly behind the colon without line feed indent format.
6. dedicated class methods
Different from common methods. After defining special methods in a class, you should not explicitly call them. Instead, Python will automatically call them in some cases.
Obtain and set data items.
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 a [1] calls the _ getitem _ method. it is equal to a. _ getitem _ (1)
Similar to the _ getitem _ method, the _ setitem _ method is used __
For example, the above Class A defines:
def __setitem__(self, key, item): self.li[key] = item
Then, call this method as follows:
A [1] = 0 it is equal to calling a. _ setitem _ (1, 0)
7. advanced dedicated class methods
Similar to _ getitem _ setitem _. there are some special functions as follows:
def __repr__(self): return repr(self.li)
This special method is used to represent the string of this object. calling it is through the built-in function repr (). For example
repr(a)
This repr () can work on any object.
In fact, in the interaction window, you only need to enter the variable name and press Enter. Then, use repr to display the variable value.
def __cmp__(self, x): if isinstance(x, A): return cmp(self.li, x.li)
It is used to compare whether two instances self and x are equal. when calling it, it is as follows:
a = A()b = A()a == b
Here we compare whether a and B are equal. it is the same as calling a. cmp (B ).
def __len__(self): return len(self.li)
It is used to return the length of an object. it is called when len (object) is used.
You can use it to specify a desired logical length value.
def __delitem__(self, key): del self.li[key]
This function is called when the del object [key] is called.
Class 8 attributes
Class attribute refers to something like a static member in c ++.
Python can also have class attributes. for example:
class A : l = [1, 2, 3]
You can reference (Modify) a class or reference (Modify) an instance. for example:
A.l
Or
a.__class__.l
9 private functions
Python also has the concept of "private:
Private functions cannot be called outside their modules.
Private class methods cannot be called outside their classes.
Private attributes cannot be accessed from outside their classes.
In Python, there are only two types of functions: private and public. there is no protection concept. to distinguish between public and private, you can see the function. class method. class attribute name.
The name of a private object starts with _. (however, the special method mentioned above (for example, _ getitem _) is not private ).