Python 简明教程

Python - OOP Concepts

OOP 是一个缩写,表示 Object-oriented programming 范式。它被定义为一种编程模型,它使用了 objects 的概念,后者指的是具有状态和行为的现实世界实体。本章可帮助你成为在 Python 语言中使用面向对象编程支持的专家。

OOP is an abbreviation that stands for Object-oriented programming paradigm. It is defined as a programming model that uses the concept of objects which refers to real-world entities with state and behavior. This chapter helps you become an expert in using object-oriented programming support in Python language.

Python 是一种支持面向对象编程的编程语言。这使得可以简单地创建和使用类和对象。如果你之前没有面向对象编程的经验,那么你找对地方了。让我们通过讨论面向对象编程 (OOP) 的一个简短简介来帮助你入门。

Python is a programming language that supports object-oriented programming. This makes it simple to create and use classes and objects. If you do not have any prior experience with object-oriented programming, you are at the right place. Let’s start by discussing a small introduction of Object-Oriented Programming (OOP) to help you.

Procedural Oriented Approach

50 年代和 60 年代开发的早期编程语言被认为是过程化(或面向过程)语言。

Early programming languages developed in 50s and 60s are recognized as procedural (or procedure oriented) languages.

计算机程序描述执行特定任务的步骤,通过按逻辑顺序编写一系列指令。更复杂的程序的逻辑被分解为更小但独立且可重用的语句块,称为函数。

A computer program describes procedure of performing certain task by writing a series of instructions in a logical order. Logic of a more complex program is broken down into smaller but independent and reusable blocks of statements called functions.

每个函数都是以一种可与程序中的其他函数接口的方式编写的。属于函数的数据可以轻松以参数形式与其他函数共享,并且被调用的函数可以将它的结果返回给调用函数。

Every function is written in such a way that it can interface with other functions in the program. Data belonging to a function can be easily shared with other in the form of arguments, and called function can return its result back to calling function.

与过程化方法相关的突出问题如下:

Prominent problems related to procedural approach are as follows −

  1. Its top-down approach makes the program difficult to maintain.

  2. It uses a lot of global data items, which is undesired. Too many global data items would increase memory overhead.

  3. It gives more importance to process and doesn’t consider data of same importance and takes it for granted, thereby it moves freely through the program.

  4. Movement of data across functions is unrestricted. In real-life scenario where there is unambiguous association of a function with data it is expected to process.

Python - OOP Concepts

在现实世界中,我们处理的对象(如学生、雇员、发票、汽车等)。对象不仅是数据,也不仅仅是函数,而是两者的结合。每个现实世界对象都有与其相关的属性和行为。

In the real world, we deal with and process objects, such as student, employee, invoice, car, etc. Objects are not only data and not only functions, but combination of both. Each real-world object has attributes and behavior associated with it.

oop concepts

Attributes

  1. Name, class, subjects, marks, etc., of student

  2. Name, designation, department, salary, etc., of employee

  3. Invoice number, customer, product code and name, price and quantity, etc., in an invoice

  4. Registration number, owner, company, brand, horsepower, speed, etc., of car

每个属性都将具有与之关联的值。属性等同于数据。

Each attribute will have a value associated with it. Attribute is equivalent to data.

Behavior

处理与对象关联的属性。

Processing attributes associated with an object.

  1. Compute percentage of student’s marks

  2. Calculate incentives payable to employee

  3. Apply GST to invoice value

  4. Measure speed of car

行为等同于函数。在现实生活中,属性和行为并非彼此独立,而是共存的。

Behavior is equivalent to function. In real life, attributes and behavior are not independent of each other, rather they co-exist.

面向对象方法最重要的特征是将属性及其功能定义为称为类的单个单元。它用作具有类似属性和行为的所有对象的蓝图。

The most important feature of object-oriented approach is defining attributes and their functionality as a single unit called class. It serves as a blueprint for all objects having similar attributes and behavior.

面向对象编程中,类定义了它的对象拥有什么属性,以及它的行为。另一方面,对象是类的实例。

In OOP, class defines what are the attributes its object has, and how is its behavior. Object, on the other hand, is an instance of the class.

Principles of OOPs Concepts

面向对象编程范例具有以下原则特征:

Object-oriented programming paradigm is characterized by the following principles −

  1. Class

  2. Object

  3. Encapsulation

  4. Inheritance

  5. Polymorphism

principles of oop

Class & Object

类是对象的用户定义原型,它定义了一组表征类的任何对象的属性。属性是数据成员(类变量和实例变量)和方法,通过点表示法访问。

A class is an user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.

对象是指某个类的实例。例如,名为 obj 的属于类 Circle 的对象是该类的实例。由类定义的数据结构的唯一实例。对象包含数据成员(类变量和实例变量)和方法。

An object refers to an instance of a certain class. For example, an object named obj that belongs to a class Circle is an instance of that class. A unique instance of a data structure that is defined by its class. An object comprises both data members (class variables and instance variables) and methods.

Example

以下示例说明如何用 Python 创建类及其对象。

The below example illustrates how to create a class and its object in Python.

# defining class
class Smartphone:
   # constructor
   def __init__(self, device, brand):
      self.device = device
      self.brand = brand

   # method of the class
   def description(self):
      return f"{self.device} of {self.brand} supports Android 14"

# creating object of the class
phoneObj = Smartphone("Smartphone", "Samsung")
print(phoneObj.description())

执行以上代码,将显示以下输出:

On executing the above code, it will display the following output −

Smartphone of Samsung supports Android 14

Encapsulation

类的数据成员仅供类内定义的函数处理。另一方面,类函数可从类上下文外部访问。因此,对象数据对外部类环境隐藏。类函数(也称为方法)封装对象数据,防止对它的不当访问。

Data members of class are available for processing to functions defined within the class only. Functions of class on the other hand are accessible from outside class context. So object data is hidden from environment that is external to class. Class function (also called method) encapsulates object data so that unwarranted access to it is prevented.

Example

在此示例中,我们使用封装概念来设定桌面的价格。

In this example, we are using the concept of encapsulation to set the price of desktop.

class Desktop:
   def __init__(self):
      self.__max_price = 25000

   def sell(self):
      return f"Selling Price: {self.__max_price}"

   def set_max_price(self, price):
      if price > self.__max_price:
         self.__max_price = price

# Object
desktopObj = Desktop()
print(desktopObj.sell())

# modifying the price directly
desktopObj.__max_price = 35000
print(desktopObj.sell())

# modifying the price using setter function
desktopObj.set_max_price(35000)
print(desktopObj.sell())

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Selling Price: 25000
Selling Price: 25000
Selling Price: 35000

Inheritance

OOP 的软件建模方法,能让你扩展现有类的能力,以便建立新类,而不用从头开始创建。在 OOP 术语中,现有的类称为基类或父类,而新类称为子类。

A software modelling approach of OOP enables extending capability of an existing class to build new class instead of building from scratch. In OOP terminology, existing class is called base or parent class, while new class is called child or sub class.

子类从父类继承数据定义和方法。这有助于重复使用已有的功能。子类可以添加更多定义或重新定义一个基类函数。

Child class inherits data definitions and methods from parent class. This facilitates reuse of features already available. Child class can add few more definitions or redefine a base class function.

Syntax

衍生类被声明的方式与他们的父类非常相似;但是,类名后面给出了要继承的基类的列表:

Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name −

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite

Example

以下示例展示了 Python 中的继承概念:

The following example demonstrates the concept of Inheritance in Python −

#!/usr/bin/python
# define parent class
class Parent:
   parentAttr = 100
   def __init__(self):
      print ("Calling parent constructor")

   def parentMethod(self):
      print ("Calling parent method")

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print ("Parent attribute :", Parent.parentAttr)

# define child class
class Child(Parent):
   def __init__(self):
      print ("Calling child constructor")

   def childMethod(self):
      print ("Calling child method")

# instance of child
c = Child()
# child calls its method
c.childMethod()
# calls parent's method
c.parentMethod()
# again call parent's method
c.setAttr(200)
# again call parent's method
c.getAttr()

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

类似地,你可以像下面这样从多个父类派生一个类:

Similar way, you can drive a class from multiple parent classes as follows −

class A:        # define your class A
.....

class B:         # define your class B
.....

class C(A, B):   # subclass of A and B
.....

你可以使用 issubclass() 或 isinstance() 函数来检查两个类和实例的关系。

You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.

  1. The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.

  2. The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class

Polymorphism

多态是希腊语单词,意为具有多种形式。在 OOP 中,当每个子类为基类中的抽象方法提供自己的实现时,就发生了多态。

Polymorphism is a Greek word meaning having multiple forms. In OOP, polymorphism occurs when each sub class provides its own implementation of an abstract method in base class.

你总是可以重写父类的函数。重写父函数的原因之一可能是你希望在子类中实现特殊或不同的功能。

You can always override your parent class methods. One reason for overriding parent’s methods is because you may want special or different functionality in your subclass.

Example

在此示例中,我们重写了父函数。

In this example, we are overriding the parent’s method.

# define parent class
class Parent:
   def myMethod(self):
      print ("Calling parent method")

# define child class
class Child(Parent):
   def myMethod(self):
      print ("Calling child method")

# instance of child
c = Child()
# child calls overridden method
c.myMethod()

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Calling child method

Base Overloading Methods in Python

下表列出了一些你可以在自己的类中重写的通用功能:

Following table lists some generic functionality that you can override in your own classes −

Sr.No.

Method, Description & Sample Call

1

init ( self [,args…​] ) Constructor (with any optional arguments) Sample Call : obj = className(args)

2

del( self ) Destructor, deletes an object Sample Call : del obj

3

repr( self ) Evaluable string representation Sample Call : repr(obj)

4

str( self ) Printable string representation Sample Call : str(obj)

5

cmp ( self, x ) Object comparison Sample Call : cmp(obj, x)

Overloading Operators in Python

假设你创建了一个表示二维向量的 Vector 类,当你使用加号运算符给它们相加时会发生什么?Python 很可能会向你大喊大叫。

Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.

然而,你可以在类中定义 add 方法来执行矢量加法,然后加号运算符便会按照预期的那样工作:

You could, however, define the add method in your class to perform vector addition and then the plus operator would behave as per expectation −

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)

   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Vector(7,8)