面向对象
Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对象是很容易的。
相关概念
1、类(Class):
用于描述具有相同属性和方法的对象集合。它定义集合中每个对象共有的属性和方法。对象是类的实例。
[En]
Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. Object is an instance of a class.
2、方法:
类中定义的函数。
3、类变量:
类变量在整个实例化对象中都是通用的。类变量在类中定义,在函数体外定义。类变量通常不用作实例变量。
[En]
Class variables are common throughout the instantiated object. Class variables are defined in the class and outside the function body. Class variables are not usually used as instance variables.
4、数据成员:
类变量或实例变量用于处理与类及其实例对象相关的数据。
[En]
Class variables or instance variables are used to process data related to a class and its instance objects.
5、方法重写:
如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
6、局部变量:
该方法中定义的变量仅作用于当前实例的类。
[En]
The variables defined in the method act only on the class of the current instance.
7、实例变量:
在类的声明中,属性是用变量来表示的,这种变量就称为实例变量,实例变量就是一个用 self 修饰的变量。
8、继承:
即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类,这是模拟”是一个(is-a)”关系(例图,Dog是一个Animal)。
9、实例化:
创建类的实例,类的具体对象。
[En]
Create an instance of a class, a concrete object of the class.
10、对象:
由类定义的数据结构的实例。该对象包括两个数据成员(类变量和实例变量)和方法。
[En]
An instance of a data structure defined by a class. The object includes two data members (class variables and instance variables) and methods.
语法格式
class ClassName:
<statement-1>
.
.
.
<statement-N>
#!/usr/bin/python3 class MyClass: """一个简单的类实例""" i = 12345 def f(self): return 'hello world' # 实例化类x = MyClass() # 访问类的属性和方法print("MyClass 类的属性 i 为:", x.i)print("MyClass 类的方法 f 输出为:", x.f())
Original: https://blog.51cto.com/apple0/5574685
Author: 最爱大苹果
Title: 极客编程python入门-面向对象5/7
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/500797/
转载文章受原作者版权保护。转载请注明原作者出处!