Home Backend Development Python Tutorial Detailed explanation of python objects and object-oriented technology

Detailed explanation of python objects and object-oriented technology

Aug 04, 2016 am 08:55 AM
python object object-oriented

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

Copy after login

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

Copy after login

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

Copy after login

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

Copy after login

In this way, the imported name can be used directly without passing the module name. For example:

>>> FunctionType
<type 'function'>

Copy after login

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. "

Copy after login

The constructor of the

class is:

__init__

Copy after login

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)

Copy after login

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. '

Copy after login

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

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

Copy after login

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 = []

Copy after login

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]

Copy after login

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

Copy after login

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)

Copy after login

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)

Copy after login

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)

Copy after login

It is used to compare whether two instances self and x are equal. It is called as follows:

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

Copy after login

这里比较 a和b是否相等. 和调用 a.cmp(b) 一样

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

Copy after login

它用来返回对象的长度. 在使用 len(对象) 的时候会调用它.
用它可以指定一个你希望的逻辑长度值.

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

Copy after login

在调用 del 对象[key] 时会调用这个函数.

8 类属性

类属性指的是象c++中静态成员一类的东西.

Python中也可以有类属性. 例如:

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

Copy after login

可以通过类来引用(修改). 或者通过实例来引用(修改). 如:

A.l

Copy after login

a.__class__.l

Copy after login

9 私有函数

Python中也有"私有"这个概念:

私有函数不可以从它们的模块外边被调用.
私有类方法不能从它们的类外边被调用.
私有属性不能从它们的类外边被访问.

Python中只有私有和公有两种. 没有保护的概念. 而区分公有还是私有是看函数. 类方法. 类属性的名字.

私有的东西的名字以 __ 开始. (但前边说的专用方法(如__getitem__)不是私有的).

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python文件与目录操作技巧汇总》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles