《Python数据分析技术栈》第02章 02 面向对象编程(Object-oriented programming)

发布时间:2024年01月19日

02 面向对象编程(Object-oriented programming)

《Python数据分析技术栈》第02章 02 面向对象编程(Object-oriented programming)

Object-oriented programming (also commonly called “OOPS”) emerged as an alternative to procedural programming, which was the traditional programming methodology.

面向对象编程(通常也称为 “OOPS”)是作为程序编程的替代方法而出现的,程序编程是传统的编程方法。

Procedural programming involved sequential execution of a program using a series of steps. One major drawback of procedural programming is the presence of global variables that are vulnerable to accidental manipulation. OOPS offers several advantages vis-à-vis procedural programming, including the ability to reuse code, doing away with global variables, preventing unauthorized access to data, and providing the ability to manage code complexity.

程序设计涉及使用一系列步骤顺序执行程序。过程式编程的一个主要缺点是存在全局变量,容易受到意外操作的影响。与过程式编程相比,OOPS 有几个优点,包括可以重复使用代码、消除全局变量、防止未经授权访问数据,以及提供管理代码复杂性的能力。

Python follows the object-oriented paradigm. Classes and objects form the building blocks of object-oriented programming. Classes provide the blueprint or structure, while objects implement this structure. Classes are defined using the class keyword.

Python 遵循面向对象范式。类和对象构成了面向对象编程的基石。类提供蓝图或结构,而对象则实现这种结构。类是用 class 关键字定义的。

As an example, say you have a class named “Baby” with attributes as the name of the baby, its gender, and weight. The methods (or the functions defined within a class) for this class could be the actions performed by a baby like smiling, crying, and eating. An instance/object is an implementation of the class and has its own set of attributes and methods. In this example, each baby would have its unique characteristics (data) and behavior (functionality)。

例如,您有一个名为 "婴儿 "的类,其属性包括婴儿的姓名、性别和体重。这个类的方法(或类中定义的函数)可以是婴儿的动作,如微笑、哭泣和进食。实例/对象是类的实现,拥有自己的属性和方法集。在这个例子中,每个婴儿都有自己独特的特征(数据)和行为(功能)。

A class can have a set of attributes or variables, which may be either class variables or instance variables. All instances of the class share class variables, whereas instance variables are unique to each instance.

一个类可以有一组属性或变量,它们可以是类变量,也可以是实例变量。类的所有实例共享类变量,而实例变量则是每个实例独有的。

Let us see how classes are defined in Python, using the following example:

让我们以下面的例子来看看 Python 中如何定义类:

# example of a class
class Rectangle:
    sides = 4

    def __init__(self, l, b):
        self.length = l
        self.breadth = b

    def area(self):
        print("Area:", self.length * self.breadth)


my_rectangle = Rectangle(4, 5)
my_rectangle.area()

The class keyword is followed by the name of a class and a colon sign. Following this, we are defining a class variable named “sides”, and initializing it to 4. This variable is common to all objects of the class.

类关键字后面是类名和冒号。接下来,我们将定义一个名为 "sides "的类变量,并将其初始化为 4。

After this, there is a constructor function that sets or initializes the variables. Note the special syntax of the constructor function - a space follows the def keyword and then two underscore signs, the init keyword, again followed by two underscore signs.

之后是一个构造函数,用于设置或初始化变量。请注意构造函数的特殊语法–def 关键字后有一个空格,然后是两个下划线符号,init 关键字后也是两个下划线符号。

The first parameter of any method defined in a class is the self keyword, which refers to an instance of the class. Then come the initialization parameters, “l” and “b”, that refer to the length and breadth of the rectangle. These values are provided as arguments when we create the object. The instance variables, “self.length” and “self.breadth”, are initialized using the parameters mentioned earlier. This is followed by another method that calculates the area of the rectangle. Remember that we need to add self as a parameter whenever we define any method of a class.

类中定义的任何方法的第一个参数都是 self 关键字,它指的是类的实例。然后是初始化参数 "l "和 “b”,它们指的是矩形的长度和宽度。这些值在我们创建对象时作为参数提供。实例变量 "self.length "和 "self.breadth "使用前面提到的参数进行初始化。接下来是另一个计算矩形面积的方法。请记住,每当我们定义一个类的任何方法时,都需要将 self 添加为参数。

Once the class is defined, we can define an instance of this class, also called an object. We create an object just like we would create a variable, give it a name, and initialize it. “my_rectangle” is the name of the object/instance created, followed by an ‘=’ sign.

一旦定义了类,我们就可以定义该类的实例,也称为对象。我们创建对象就像创建变量一样,给它起个名字并初始化。"my_rectangle “是创建对象/实例的名称,后面跟一个”="号。

We then mention the name of the class and the parameters used in the constructor function to initialize the object. We are creating a rectangle with length as 4 and breadth as 5. We then call the area method to calculate the area, which calculates and prints the area.

然后,我们提及类的名称和构造函数中用于初始化对象的参数。我们将创建一个长为 4、宽为 5 的矩形,然后调用 area 方法计算面积,计算并打印出面积。

面向对象的编程原则(Object-oriented programming principles)

The main principles of object-oriented programming are encapsulation, polymorphism, data abstraction, and inheritance. Let us look at each of these concepts.

面向对象编程的主要原则是封装、多态性、数据抽象和继承。让我们逐一了解这些概念。

Encapsulation: Encapsulation refers to binding data (variables defined within a class) with the functionality (methods) that can modify it. Encapsulation also includes data hiding, since the data defined within the class is safe from manipulation by any function defined outside the class. Once we create an object of the class, its variables can be accessed and modified only by the methods (or functions) associated with the object.

封装: 封装是指将数据(类中定义的变量)与可以修改数据的功能(方法)绑定在一起。封装还包括数据隐藏,因为类内定义的数据不会被类外定义的任何函数操作。一旦我们创建了类的对象,就只能通过与该对象相关联的方法(或函数)来访问和修改其变量。

Let us consider the following example:

请看下面的例子:

class Circle():
    def __init__(self, r):
        self.radius = r

    def area(self):
        return 3.14 * self.r * self.r


c = Circle(5)
print(c.radius)  # correct way of accessing instance variable

Here, the class Circle has an instance variable, radius, and a method, area. The variable, radius, can only be accessed using an object of this class and not by any other means, as shown in the following statement.

在这里,类 Circle 有一个实例变量 radius 和一个方法 area。变量 radius 只能通过该类的对象访问,而不能通过任何其他方式访问,如以下语句所示。

c.radius #correct way of accessing instance variable
radius #incorrect, leads to an error

多态性(Polymorphism)

Polymorphism (one interface, many forms) provides the ability to use the same interface (method or function) regardless of the data type.

多态性(一个接口,多种形式)提供了无论数据类型如何都能使用相同接口(方法或函数)的能力。

Let us understand the principle of polymorphism using the len function.

让我们用 len 函数来理解多态性原理。

#using the len function with a string
len("Hello")
#using the len function with a list
len([1,2,3,4])
#using the len function with a tuple
len((1,2,3))
#using the len function with a dictionary
len({'a':1,'b':2})

The len function, which calculates the length of its argument, can take any type of argument. We passed a string, list, tuple, and dictionary as arguments to this function, and the function returned the length of each of these objects. There was no need to write a separate function for each data type.

计算参数长度的 len 函数可以接受任何类型的参数。我们将字符串、列表、元组和字典作为参数传递给该函数,函数会返回每个对象的长度。无需为每种数据类型编写单独的函数。

继承(Inheritance)

Inheritance refers to the ability to create another class, called a child class, from its parent class. A child class inherits some attributes and functions from the parent class but may also have its own functionality and variables.

继承是指从父类创建另一个类(称为子类)的能力。子类继承父类的某些属性和功能,但也可能拥有自己的功能和变量。

An example of inheritance in Python is demonstrated in the following.

下面是 Python 中继承的一个示例。

# inheritance
class Mother():
    def __init__(self, fname, sname):
        self.firstname = fname
        self.surname = sname

    def nameprint(self):
        print("Name:", self.firstname + " " + self.surname)


class Child(Mother):
    pass

The parent class is called “Mother”, and its attributes “firstname” and “surname” are initialized using the init constructor method. The child class, named “Child”, is inherited from the “Mother” class. The name of the parent class is passed as an argument when we define the child class. The keyword pass instructs Python that nothing needs to be done for the child class (this class just inherits everything from the parent class without adding anything).

父类名为 “母亲”,其属性 "名 "和 "姓 "使用 init 构造函数方法初始化。子类名为 “Child”,继承自 "Mother "类。当我们定义子类时,父类的名称会作为参数传递。关键字 pass 指示 Python,子类不需要做任何事情(该类只是继承了父类的所有内容,而没有添加任何东西)。

However, even if the child class does not implement any other method or add any extra attribute, the keyword pass is essential to prevent any error from being thrown.

不过,即使子类没有实现任何其他方法或添加任何额外属性,关键字 pass 对于防止抛出任何错误也是必不可少的。

数据抽象(Data abstraction)

Data abstraction is the process of presenting only the functionality while hiding the implementation details. For instance, a new user to Whatsapp needs to only learn its essential functions like sending messages, attaching photos, and placing calls, and not how these features were implemented by the developers who wrote the code for this app.

数据抽象是只展示功能而隐藏实现细节的过程。例如,Whatsapp 的新用户只需要了解其基本功能,如发送消息、附加照片和拨打电话,而不需要了解为该应用程序编写代码的开发人员是如何实现这些功能的。

In the following example, where we declare an object of the “Circle” class and calculate the area using the area method, we do not need to know how the area is being calculated when we call the area method.

在下面的示例中,我们声明了一个 "圆 "类对象,并使用 area 方法计算面积。

class Circle():
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14 * self.r * self.r


circle1 = Circle(3)
circle1.area()
文章来源:https://blog.csdn.net/qq_37703224/article/details/135687967
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。