初识python中的类

5d158d2ce6dd7737

类是什么

类是一种组合信息和行为的方式。举个例子,我们考虑在物理仿真中建造一个飞船。首先要做的就是追踪飞船的坐标(x, y)。飞船在代码中的形式如下:

class Rocket():          def __init__(self):         # Each rocket has an (x, y) position         self.x = 0         self.y = 0

在类中要做的第一件事就是定义 __init__ 函数。当对象被创建时,__init__ 函数就会执行,为需要的参数设置初始值。self 以后会介绍,总之,它是一个可以让你访问类中变量的语法。

目前为止,Rocket 类存储了两部分的信息,但是它什么也做不了。Rocket 类的第一个核心的行为是:移动。代码如下所示:

class Rocket():     # Rocket simulates a rocket ship for a game,     #  or a physics simulation.          def __init__(self):         # Each rocket has an (x,y) position.         self.x = 0         self.y = 0              def move_up(self):         # Increment the y-position of the rocket.         self.y += 1

现在 Rocket 类存储了一些信息,并且能做一些事情。但是你还没有真正建造一艘自己的飞船。接下来就是建造自己的飞船了,代码如下:

class Rocket():     # Rocket simulates a rocket ship for a game,     #  or a physics simulation.          def __init__(self):         # Each rocket has an (x,y) position.         self.x = 0         self.y = 0         print("Created")              def move_up(self):         # Increment the y-position of the rocket.         self.y += 1  # Create a Rocket object. my_rocket = Rocket() print(my_rocket)

为了使用类,创建一个变量如 my_rocket 。然后用类名后跟圆括号给这个变量赋值。这样就创建了一个类的对象。对象是类的实例,它有类中所有变量的拷贝,并且可以做类中所有定义的行为。在上述代码中,你可以看到变量 my_rocket 是一个来自 __main__ 程序文件中的 Rocket 对象,这个程序文件存储在内存中的特定位置。

有了类你就可以定义对象并且使用它的方法。实例如下:

class Rocket():     # Rocket simulates a rocket ship for a game,     #  or a physics simulation.          def __init__(self):         # Each rocket has an (x,y) position.         self.x = 0         self.y = 0              def move_up(self):         # Increment the y-position of the rocket.         self.y += 1  # Create a Rocket object, and have it start to move up. my_rocket = Rocket() print("Rocket altitude:", my_rocket.y)  my_rocket.move_up() print("Rocket altitude:", my_rocket.y)

使用对象名和点符号来访问对象的变量和方法。因此为了得到 my_rocket 的 y 值,使用 my_rocket.y 。使用 my_rocket.move_up() 来访问 move_up() 函数。

一旦类定义好,你就可以创建任意数量的对象。每个对象都有独立的变量空间,互不影响。如下所示:

class Rocket():     # Rocket simulates a rocket ship for a game,     #  or a physics simulation.          def __init__(self):         # Each rocket has an (x,y) position.         self.x = 0         self.y = 0              def move_up(self):         # Increment the y-position of the rocket.         self.y += 1          # Create a fleet of 5 rockets, and store them in a list. my_rockets = [] for x in range(0,5):     new_rocket = Rocket()     my_rockets.append(new_rocket)  # Show that each rocket is a separate object. for rocket in my_rockets:     print(rocket)

如果你知道列表推导式,你也可以将代码改写成如下形式:

class Rocket():          # Rocket simulates a rocket ship for a game,# Rocket      #  or a physics simulation.          def __init__(self):         # Each rocket has an (x,y) position.         self.x = 0         self.y = 0              def move_up(self):         # Increment the y-position of the rocket.         self.y += 1          # Create a fleet of 5 rockets, and store them in a list. my_rockets = [Rocket() for x in range(0,5)]  # Show that each rocket is a separate object. for rocket in my_rockets:     print(rocket)

每一个 rocket 在内存中都是独立的。拥有自己的 x 和 y 。你可以通过移动不同的飞船来证明这点。如下所示:

class Rocket():     # Rocket simulates a rocket ship for a game,     #  or a physics simulation.          def __init__(self):         # Each rocket has an (x,y) position.         self.x = 0         self.y = 0              def move_up(self):         # Increment the y-position of the rocket.         self.y += 1          # Create a fleet of 5 rockets, and store them in a list. my_rockets = [Rocket() for x in range(0,5)]  # Move the first rocket up. my_rockets[0].move_up()  # Show that only the first rocket has moved. for rocket in my_rockets:     print("Rocket altitude:", rocket.y)

现在类的语法对你来说或许不是很明了。但是考虑不用类来创建一个飞船。你或许会将 x 和 y 存储在一个字典中,即便是定义很少的飞船都需要写出很多丑陋的,难以维护的代码。当加入越来越多的特性,代码会变得越来越难以维护。这时候你就会发现基于真实世界模型的类是多么的高效。