1.2.9. 面向对象编程(OOP)¶
Python supports object-oriented programming (OOP). The goals of OOP are:
- to organize the code, and
- to re-use code in similar contexts.
这里有一个小例子:我们创建一个Student类,它是一个我们将能够使用的收集了几个自定义函数(方法)和变量(属性)的对象:
>>> class Student(object):
... def __init__(self, name):
... self.name = name
... def set_age(self, age):
... self.age = age
... def set_major(self, major):
... self.major = major
...
>>> anna = Student('anna')
>>> anna.set_age(21)
>>> anna.set_major('physics')
In the previous example, the Student class has __init__
, set_age
and set_major
methods. Its attributes are name
, age
and major
. We can call these methods and attributes with the following notation: classinstance.method
or classinstance.attribute
. __init__
构造函数是我们调用的一种特殊方法:MyClass(init parameters if any)
。
Now, suppose we want to create a new class MasterStudent with the same methods and attributes as the previous one, but with an additional internship
attribute. 我们不会复制上一个类,而是继承:
>>> class MasterStudent(Student):
... internship = 'mandatory, from March to June'
...
>>> james = MasterStudent('james')
>>> james.internship
'mandatory, from March to June'
>>> james.set_age(23)
>>> james.age
23
MasterStudent类继承Student的属性和方法。
由于类和面向对象的编程,我们可以组织不同类的代码,这些类对应于我们遇到的不同对象(一个Experiment类、一个Image类、一个Flow类等)以及它们自己的方法和属性。然后,我们可以使用继承来考虑基类的变化并重用代码。例如:从Flow基类,我们可以创建派生的StokesFlow、TurbulentFlow、PotentialFlow等。