


Detailed explanation of python objects and object-oriented technology
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 form of module name.XXX. For example:
>>> import types >>> types.FunctionType <type 'function'> >>> FunctionType
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
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
In this way, the imported name can be used directly without passing the module name. For example:
>>> FunctionType <type 'function'>
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. "The constructor of the
class is:
__init__
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)
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. '
We can also get its class through its instance. This is through its __class__ attribute. For example:
>>> a.__class__ <class __main__.A at 0x011394B0>
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 = []
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]
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
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)
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)
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)
It is used to compare whether two instances self and x are equal. It is called as follows:
a = A() b = A() a == b
这里比较 a和b是否相等. 和调用 a.cmp(b) 一样
def __len__(self): return len(self.li)
它用来返回对象的长度. 在使用 len(对象) 的时候会调用它.
用它可以指定一个你希望的逻辑长度值.
def __delitem__(self, key): del self.li[key]
在调用 del 对象[key] 时会调用这个函数.
8 类属性
类属性指的是象c++中静态成员一类的东西.
Python中也可以有类属性. 例如:
class A : l = [1, 2, 3]
可以通过类来引用(修改). 或者通过实例来引用(修改). 如:
A.l
或
a.__class__.l
9 私有函数
Python中也有"私有"这个概念:
私有函数不可以从它们的模块外边被调用.
私有类方法不能从它们的类外边被调用.
私有属性不能从它们的类外边被访问.
Python中只有私有和公有两种. 没有保护的概念. 而区分公有还是私有是看函数. 类方法. 类属性的名字.
私有的东西的名字以 __ 开始. (但前边说的专用方法(如__getitem__)不是私有的).
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python文件与目录操作技巧汇总》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
