Python 类和对象

Python 是面向对象的编程语言,Python 类和对象是 Python 编程语言的核心构建要素。

Python 班级

到目前为止,你们都应该已经了解了 Python 数据类型。如果你记得,python 中的基本数据类型一次仅指一种数据类型。

简单的Python课堂声明

以下是 Python 类定义的基本结构。

1class ClassName:  
2    # list of python class variables  
3    # python class constructor  
4    # python class method definitions

现在,让我们用真实的例子来工作。

 1#definition of the class starts here  
 2class Person:  
 3    #initializing the variables  
 4    name = ""  
 5    age = 0  
 6
 7    #defining constructor  
 8    def __init__(self, personName, personAge):  
 9        self.name = personName  
10        self.age = personAge  
11
12    #defining class methods  
13    def showName(self):  
14        print(self.name)  
15
16    def showAge(self):  
17        print(self.age)  
18
19    #end of the class definition  
20
21# Create an object of the class  
22person1 = Person("John", 23)  
23#Create another object of the same class  
24person2 = Person("Anne", 102)  
25#call member methods of the objects  
26person1.showAge()  
27person2.showName()

This example is pretty much self-explanatory. As we know, the lines starting with "#" are python comments. The comments explain the next executable steps. This code produces the following output. Output of python class example

Python 类的定义

1class Person:

这个行标志着类的类定义的开始。

Python 类变量

1#initializing the variables  
2    name = ""  
3    age = 0

名称年龄类的两个成员变量,每当我们声明这个类的对象时,它将包含这两个变量作为其成员。

Python 类建设者

1#defining constructor  
2    def __init__(self, personName, personAge):  
3        self.name = personName  
4        self.age = personAge

Python 类构建器是创建一个类的新对象时执行的第一个代码。 首先,构建器可以用来将值放在成员变量中。 您也可以在构建器中打印消息以确认对象是否被创建。 一旦我们了解了 python 的继承,我们将学习构建器的更大作用。 构建器方法始于 defininit__。 之后,第一个参数必须是自我,因为它传递了对类本身的实例的参考。

Python 类方法

1#defining python class methods  
2    def showName(self):  
3        print(self.name)

方法如下所述:

1def method_name(self, parameter 1, parameter 2, …….)
2    statements……..
3    return value (if required)

在预先列出的示例中,我们已经看到,方法 showName() 打印了对象的名称值,我们会在另一天讨论更多关于 python 方法的内容。

Python 类对象

1# Create an object of the class  
2person1 = Person("Richard", 23)  
3#Create another object of the same class  
4person2 = Person("Anne", 30)  
5
6#call member methods of the objects  
7person1.showAge()
8person2.showName()

在 python 中创建对象的方式非常简单. 首先,你把新的对象的名称,然后是分配操作员和与参数组成的类的名称(如构建器中定义)。 请记住,参数的数量和类型应该与在构建器函数中收到的参数兼容。

1#print the name of person1 by directly accessing the ‘name’ attribute
2print(person1.name)

这是关于 Python 类的基本知识的一切. 随着我们在随后的教程中了解 Python 对象导向的特性,如遗传、多样性,我们将更多地了解 Python 类及其功能。 直到那时,快乐的编码和再见! 如果您有任何问题,请自由发表评论。 参考: Python.org 文档

Published At
Categories with 技术
Tagged with
comments powered by Disqus