Object Oriented Python 简明教程
Object Oriented Python - Introduction
编程语言不断涌现,不同的方法学也是如此。面向对象编程就是这样一种方法,在过去几年中变得非常流行。
Programming languages are emerging constantly, and so are different methodologies.Object-oriented programming is one such methodology that has become quite popular over past few years.
本节讲述 Python 编程语言作为面向对象编程语言的特性。
This chapter talks about the features of Python programming language that makes it an object-oriented programming language.
Language Programming Classification Scheme
Python 可归类为面向对象编程方法。下图说明了各种编程语言的特性。观察 Python 中使其成为面向对象的特性。
Python can be characterized under object-oriented programming methodologies. The following image shows the characteristics of various programming languages. Observe the features of Python that makes it object-oriented.
Langauage Classes |
Categories |
Langauages |
Programming Paradigm |
Procedural |
C, C++, C#, Objective-C, java, Go |
Scripting |
CoffeeScript, JavaScript, Python, Perl, Php, Ruby |
Functional |
Clojure, Eralang, Haskell, Scala |
Compilation Class |
Static |
C, C++, C#, Objective-C, java, Go, Haskell, Scala |
Dynamic |
CoffeeScript, JavaScript, Python, Perl, Php, Ruby, Clojure, Erlang |
Type Class |
Strong |
C#, java, Go, Python, Ruby, Clojure, Erlang, Haskell, Scala |
Weak |
C, C++, C#, Objective-C, CoffeeScript, JavaScript, Perl, Php |
Memory Class |
Managed |
Others |
Unmanaged |
What is Object Oriented Programming?
Object Oriented 意味着面向对象。换句话说,这就是对于对对象建模来说在功能上的方向。这是通过描述一组交互对象及其数据和行为对复杂系统建模时所用的众多技术之一。
Object Oriented means directed towards objects. In other words, it means functionally directed towards modelling objects. This is one of the many techniques used for modelling complex systems by describing a collection of interacting objects via their data and behavior.
Python,一种面向对象编程(OOP),是专注于使用对象和类来进行设计和构建应用程序的编程方法。面向对象编程(OOP)的主要支柱是 Inheritance, Polymorphism, Abstraction, 和 Encapsulation 。
Python, an Object Oriented programming (OOP), is a way of programming that focuses on using objects and classes to design and build applications.. Major pillars of Object Oriented Programming (OOP) are Inheritance, Polymorphism, Abstraction, ad Encapsulation.
面向对象分析(OOA)是对问题、系统或任务进行检验并识别其对象和交互的过程。
Object Oriented Analysis(OOA) is the process of examining a problem, system or task and identifying the objects and interactions between them.
Why to Choose Object Oriented Programming?
Python是在面向对象方法的基础上设计的。OOP具有以下优势-
Python was designed with an object-oriented approach. OOP offers the following advantages −
-
Provides a clear program structure, which makes it easy to map real world problems and their solutions.
-
Facilitates easy maintenance and modification of existing code.
-
Enhances program modularity because each object exists independently and new features can be added easily without disturbing the existing ones.
-
Presents a good framework for code libraries where supplied components can be easily adapted and modified by the programmer.
-
Imparts code reusability
Procedural vs. Object Oriented Programming
基于过程的编程源于结构化编程,基于 functions/procedure/routines 的概念。在面向过程的编程中,访问和更改数据非常容易。另一方面,面向对象编程(OOP)允许将问题分解为若干称为 objects 的单元,然后围绕这些对象构建数据和函数。它更强调数据而不是过程或函数。同样,在 OOP 中,数据是隐藏的,外部过程无法访问。
Procedural based programming is derived from structural programming based on the concepts of functions/procedure/routines. It is easy to access and change the data in procedural oriented programming. On the other hand, Object Oriented Programming (OOP) allows decomposition of a problem into a number of units called objects and then build the data and functions around these objects. It emphasis more on the data than procedure or functions. Also in OOP, data is hidden and cannot be accessed by external procedure.
下图中的表格显示了 POP 和 OOP 方法之间的主要区别。
The table in the following image shows the major differences between POP and OOP approach.
面向过程编程(POP)和面向对象编程(OOP)之间的差异。
Difference between Procedural Oriented Programming(POP)vs. Object Oriented Programming(OOP).
Procedural Oriented Programming |
ObjectOriented Programming |
|
Based On |
In Pop,entire focus is on data and functions |
Oops is based on a real world scenario.Whole program is divided into small parts called object |
Reusability |
Limited Code reuse |
Code reuse |
Approach |
Top down Approach |
Object focused Design |
Access specifiers |
Not any |
Public, private and Protected |
Data movement |
Data can move freely from functions to function in the system |
In Oops, data can move and communicate with each other through member functions |
Data Access |
In pop, most functions uses global data for sharing that can be accessed freely from function to function in the system |
In Oops,data cannot move freely from method to method,it can be kept in public or private so we can control the access of data |
Data Hiding |
In pop, so specific way to hide data, so little bit less secure |
It provides data hiding, so much more secure |
Overloading |
Not possible |
Functions and Operator Overloading |
Example-Languages |
C, VB, Fortran, Pascal |
C++, Python, Java, C# |
Abstraction |
Uses abstraction at procedure level |
Uses abstraction at class and object Level |
Principles of Object Oriented Programming
面向对象编程 (OOP) 基于 objects 而不是操作以及 data 而不是逻辑的概念。为了让编程语言面向对象,它应当具备一种机制来实现使用类和对象以及实现和使用基本面向对象原则和概念(即继承、抽象、封装和多态性)。
Object Oriented Programming (OOP) is based on the concept of objects rather than actions, and data rather than logic. In order for a programming language to be object-oriented, it should have a mechanism to enable working with classes and objects as well as the implementation and usage of the fundamental object-oriented principles and concepts namely inheritance, abstraction, encapsulation and polymorphism.

让我们简要了解面向对象编程的各个支柱 -
Let us understand each of the pillars of object-oriented programming in brief −
Encapsulation
此属性隐藏了不必要详细信息,并让对程序结构的管理变得更轻松。每个对象实现和状态都隐藏在定义明确的界限之后,并提供了一个用于使用它们的清晰而简单的接口。实现此操作的一种方式是使数据私有。
This property hides unnecessary details and makes it easier to manage the program structure. Each object’s implementation and state are hidden behind well-defined boundaries and that provides a clean and simple interface for working with them. One way to accomplish this is by making the data private.
Inheritance
继承也称为泛化,它允许我们捕获类和对象之间的层级关系。例如,“水果”就是“橙子”的一项概括。继承从代码重用角度来看非常有用。
Inheritance, also called generalization, allows us to capture a hierarchal relationship between classes and objects. For instance, a ‘fruit’ is a generalization of ‘orange’. Inheritance is very useful from a code reuse perspective.
Abstraction
此属性允许我们隐藏详细信息并仅公开某个概念或对象的关键特征。例如,驾驶滑板车的人知道按喇叭会发出声音,但他不知道按喇叭实际上如何产生声音。
This property allows us to hide the details and expose only the essential features of a concept or object. For example, a person driving a scooter knows that on pressing a horn, sound is emitted, but he has no idea about how the sound is actually generated on pressing the horn.
Object-Oriented Python
Python 编程的核心是 object 和 OOP ,但您不必将自己限制在通过将代码整理成类来使用 OOP。OOP 增强了 Python 的整体设计理念,并支持以整洁有效的方式编程。OOP 还支持编写更大型且更复杂的程序。
The heart of Python programming is object and OOP, however you need not restrict yourself to use the OOP by organizing your code into classes. OOP adds to the whole design philosophy of Python and encourages a clean and pragmatic way to programming. OOP also enables in writing bigger and complex programs.
Modules vs. Classes and Objects
Modules are like “Dictionaries”
在使用模块时,注意以下要点 -
When working on Modules, note the following points −
-
A Python module is a package to encapsulate reusable code.
-
Modules reside in a folder with a init.py file on it.
-
Modules contain functions and classes.
-
Modules are imported using the import keyword.
回想一下,字典是一个 key-value 对。这意味着,如果您有一个键为 EmployeID 的字典,并且您想要检索它,那么您将必须使用下列代码行 −
Recall that a dictionary is a key-value pair. That means if you have a dictionary with a key EmployeID and you want to retrieve it, then you will have to use the following lines of code −
employee = {“EmployeID”: “Employee Unique Identity!”}
print (employee [‘EmployeID])
您将需要按照以下过程处理 modules −
You will have to work on modules with the following process −
-
A module is a Python file with some functions or variables in it.
-
Import the file you need.
-
Now, you can access the functions or variables in that module with the ‘.’ (dot) Operator.
考虑一个名为 employee.py 的 module,其中有一个名为 employee 的函数。该函数的代码如下所示 −
Consider a module named employee.py with a function in it called employee. The code of the function is given below −
# this goes in employee.py
def EmployeID():
print (“Employee Unique Identity!”)
现在导入 module,然后访问函数 EmployeID −
Now import the module and then access the function EmployeID −
import employee
employee. EmployeID()
您可以像所示的那样,在其中插入一个名为 Age 的变量 −
You can insert a variable in it named Age, as shown −
def EmployeID():
print (“Employee Unique Identity!”)
# just a variable
Age = “Employee age is **”
现在,请以下面的方式访问该变量 −
Now, access that variable in the following way −
import employee
employee.EmployeID()
print(employee.Age)
现在,让我们将它与字典进行比较 −
Now, let’s compare this to dictionary −
Employee[‘EmployeID’] # get EmployeID from employee
Employee.employeID() # get employeID from the module
Employee.Age # get access to variable
请注意,Python 中有一个通用的模式 −
Notice that there is common pattern in Python −
-
Take a key = value style container
-
Get something out of it by the key’s name
当将 module 与字典进行比较时,两者相似,但有以下几点除外 −
When comparing module with a dictionary, both are similar, except with the following −
-
In the case of the dictionary, the key is a string and the syntax is [key].
-
In the case of the module, the key is an identifier, and the syntax is .key.
Classes are like Modules
模块是可存储 Python 代码的专门词典,你可以用“.”操作符访问它。类是一种将函数和数据分组放置在容器中以便你可以用“.”操作符访问它们的方式。
Module is a specialized dictionary that can store Python code so you can get to it with the ‘.’ Operator. A class is a way to take a grouping of functions and data and place them inside a container so you can access them with the ‘.‘operator.
如果你必须创建一个类似于员工模块的类,可以使用以下代码创建:
If you have to create a class similar to the employee module, you can do it using the following code −
class employee(object):
def __init__(self):
self. Age = “Employee Age is ##”
def EmployeID(self):
print (“This is just employee unique identity”)
Note - 类比模块更受青睐,因为你可以原封不动地重复使用它们,而且不会造成太多干扰。对于模块,你只能将它们与整个程序合二为一。
Note − Classes are preferred over modules because you can reuse them as they are and without much interference. While with modules, you have only one with the entire program.
Objects are like Mini-imports
类类似于 mini-module ,你可以用 instantiate 中提到的概念以类似于导入类的方式导入类。注意,当你实例化一个类时,你可以获得 object 。
A class is like a mini-module and you can import in a similar way as you do for classes, using the concept called instantiate. Note that when you instantiate a class, you get an object.
你可以实例化一个对象,类似于像调用函数那样调用一个类,如下所示:
You can instantiate an object, similar to calling a class like a function, as shown −
this_obj = employee() # Instantiatethis_obj.EmployeID() # get EmployeId from the class
print(this_obj.Age) # get variable Age
你可以使用以下三种方式中的任何一种:
You can do this in any of the following three ways −
# dictionary style
Employee[‘EmployeID’]
# module style
Employee.EmployeID()
Print(employee.Age)
# Class style
this_obj = employee()
this_obj.employeID()
Print(this_obj.Age)