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> >>> FunctionType</type>
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>", line 1, in <module> NameError: name 'FunctionType' is not defined</module></interactive>
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:
passor class class name (base class list): pass
>>> FunctionType <type></type>
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></class>
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 !

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools