Skip to content

面向对象

Python 从设计之初就已经是一门面向对象的语言,正因为如此,在 Python 中创建一个类和对象是很容易的。本章节我们将详细介绍 Python 的面向对象编程。

如果你以前没有接触过面向对象的编程语言,那你可能需要先了解一些面向对象语言的一些基本特征,在头脑里头形成一个基本的面向对象的概念,这样有助于你更容易的学习 Python 的面向对象编程。

接下来我们先来简单的了解下面向对象的一些基本特征。

面向对象技术简介

  • :用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。
  • 方法:类中定义的函数,它负责实现对象所具有的功能。
  • 类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
  • 数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据。
  • 方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
  • 局部变量:定义在方法中的变量,只作用于当前实例的类
  • 继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。
  • 实例化:创建一个类的实例,类的具体对象。
  • 对象:通过类定义的数据结构实例。对象包括两个部分:状态(state)和行为(behavior)。

和其它编程语言相比,Python 在尽可能不增加新的语法和语义的情况下加入了类机制。

Python 中的类提供了面向对象编程的所有基本功能:类的继承机制允许多个基类,派生类可以覆盖基类中的任何方法,方法中可以调用基类中的同名方法。

对象可以包含任意数量和类型的数据。

类定义

在 Python 中,我们使用class关键字来定义一个类。

python
class MyClass:
    x = 5

类对象

类对象支持两种操作:属性引用和实例化。

属性引用使用和 Python 中所有的属性引用一样的标准语法:obj.name。

类对象创建后,类命名空间中所有的命名都是有效属性名。所以如果类定义是这样:

python

#!/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())

以上创建了一个新的类实例并将该对象赋给局部变量 x,x 为空的对象。

执行以上程序输出结果为:

MyClass 类的属性 i 为: 12345
MyClass 类的方法 f 输出为: hello world

类有一个名为 init() 的特殊方法(构造方法),该方法在类实例化时会自动调用,像下面这样:

python
class MyClass:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print("Hello, my name is", self.name)

# 实例化类
x = MyClass("Alice")

# 调用方法
x.say_hello()

以上程序输出结果为:

Hello, my name is Alice

self 代表类的实例,而非类

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。

python
class Test:
    def prt(self):
        print(self)
        print(self.__class__)

t = Test()
t.prt()

以上程序输出结果为:

<__main__.Test object at 0x7f9d5d511a50>
<class '__main__.Test'>

类的方法

在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。

python
#!/usr/bin/python3

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))

# 实例化类
p = people('runoob',10,30)
p.speak()

以上程序输出结果为:

runoob 说: 我 10 岁。

类的继承

Python 支持类的继承,派生类可以继承基类中的属性和方法。

python
class Animal:
    def run(self):
        print('Animal is running...')

class Dog(Animal):
    def run(self):
        print('Dog is running...')

class Cat(Animal):
    def run(self):
        print('Cat is running...')

dog = Dog()
dog.run() # 输出结果: Dog is running...

cat = Cat()
cat.run() # 输出结果: Cat is running...

多态

多态(Polymorphism)是指允许不同类的对象对同一消息作出不同的响应。

多态在 Python 中表现为:允许将父类对象赋值给一个子类对象,而后调用子类对象的方法,实际上调用的仍然是父类的方法。

python
class Animal:
    def run(self):
        print('Animal is running...')

class Dog(Animal):
    def run(self):
        print('Dog is running...')

class Cat(Animal):
    def run(self):
        print('Cat is running...')

def run_twice(animal):
    animal.run()
    animal.run()

run_twice(Animal()) # 输出结果: Animal is running... Animal is running...
run_twice(Dog()) # 输出结果: Dog is running... Dog is running...
run_twice(Cat()) # 输出结果: Cat is running... Cat is running...

多继承

Python 支持多继承,一个子类可以同时继承多个父类。

python
class Animal:
    def run(self):
        print('Animal is running...')

class Dog(Animal):
    def run(self):
        print('Dog is running...')

class Cat(Animal):
    def run(self):
        print('Cat is running...')

class Bird(Animal):
    def run(self):
        print('Bird is running...')

class RunnableMixIn:
    def run(self):
        print('I can run!')

class FlyableMixIn:
    def fly(self):
        print('I can fly!')

class DogCat(Dog, Cat):
    pass

class DogCatBird(Dog, Cat, Bird):
    pass

class DogCatRunnable(Dog, Cat, RunnableMixIn):
    pass

class DogCatFlyable(Dog, Cat, FlyableMixIn):
    pass

dog = Dog()
dog.run() # 输出结果: Dog is running...

cat = Cat()
cat.run() # 输出结果: Cat is running...

dogcat = DogCat()
dogcat.run() # 输出结果: Dog is running...

dogcatbird = DogCatBird()
dogcatbird.run() # 输出结果: Dog is running...

dogcatrunnable = DogCatRunnable()
dogcatrunnable.run() # 输出结果: I can run!

dogcatflyable = DogCatFlyable()
dogcatflyable.fly() # 输出结果: I can fly!

方法重写

如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。

python
class Animal:
    def run(self):
        print('Animal is running...')

class Dog(Animal):
    def run(self):
        print('Dog is running...')

class Cat(Animal):
    def run(self):
        print('Cat is running...')

class Bird(Animal):
    def run(self):
        print('Bird is running...')

class DogCat(Dog, Cat):
    def run(self):
        print('DogCat is running...')

dog = Dog()
dog.run() # 输出结果: Dog is running...

cat = Cat()
cat.run() # 输出结果: Cat is running...

dogcat = DogCat()
dogcat.run() # 输出结果: DogCat is running...

类属性与方法

类的私有属性

__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs

类的方法

在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例。

self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定使用 self。

类的私有方法

__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods

类的专有方法

  • __init__ : 构造函数,在生成对象时调用
  • __del__ : 析构函数,释放对象时使用
  • __repr__ : 打印,转换
  • __setitem__ : 按照索引赋值
  • __getitem__: 按照索引获取值
  • __len__: 获得长度
  • __cmp__: 比较运算
  • __call__: 函数调用
  • __add__: 加运算
  • __sub__: 减运算
  • __mul__: 乘运算
  • __truediv__: 除运算
  • __mod__: 求余运算
  • __pow__: 乘方

运算符重载

Python 同样支持运算符重载,我们可以对类的专有方法进行重载,实例如下:

python
#!/usr/bin/python3

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)

   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

代码运行结果

Vector (7, 8)