- 1.面对对象编程
- 实例
- 实例数据(属性)
- 实例行为(方法)
- 类范围
- 2.继承
- object 基类
- Overriding
- __init__ 继承
- 3.多重继承
- 4.多态
- 5.魔法方法
- 6.自定义异常类
类是对象的集合。
一个对象包括:
- 数据(属性)
- 行为(方法)
类是对对象实例执行各种操作的函数。
class Player:
def __init__(self, x, y):
self.x = x # Any value stored on `self` is instance data
self.y = y
self.health = 100
def move(self, dx, dy):
self.x += dx
self.y += dy
def damage(self, pts):
self.health -= pts
实例
实例是在程序中操作的实际对象。
>>> a = Player(2, 3) >>> b = Player(10, 20) >>>
通过将类作为函数调用来创建的,类语句只是定义,类似于函数的定义。
实例数据(属性)每个实例都有自己的数据, 由 init() 提供。
>>> a.x 2 >>> b.x 10
另外一种属性访问方法
getattr(obj, 'name') # Same as obj.name setattr(obj, 'name', value) # Same as obj.name = value delattr(obj, 'name') # Same as del obj.name hasattr(obj, 'name') # Tests if attribute exists实例行为(方法)
实例方法是应用于对象实例的函数。
class Player:
...
# `move` is a method
def move(self, dx, dy):
self.x += dx
self.y += dy
python 中对象本身总是作为第一个参数传递。
>>> a.move(1, 2) # matches `a` to `self` # matches `1` to `dx` # matches `2` to `dy` def move(self, dx, dy):类范围
类中的方法没有定义范围。
如果想引用它,使用 self.
class Player:
...
def move(self, dx, dy):
self.x += dx
self.y += dy
def left(self, amt):
move(-amt, 0) # NO. Calls a global `move` function
self.move(-amt, 0) # YES. Calls method `move` from above.
2.继承
继承用于扩展现有对象:
#基类 Parent
class Parent:
...
#新的派生类或子类 Child
class Child(Parent):
...
当子类继承基类之后,可以使用基类方法。
#基类
class Stock:
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
def cost(self):
return self.shares * self.price
def sell(self, nshares):
self.shares -= nshares
添加新方法。
class MyStock(Stock):
def panic(self):
self.sell(self.shares)
重新定义现有方法。
class MyStock(Stock):
def cost(self):
return 1.25 * self.shares * self.price
object 基类
如果一个类没有父类,有时会看到 object 类作为基础。
object是 python 中所有对象的父对象。
通常我们并不这么做,这是 python 2 中类使用格式的保留,如果省略也隐形继承 object。
Overridingsuper()的使用:有时基类有一个现有方法,但子类想在基类的基础上扩展这个方法。
class Stock:
...
def cost(self):
return self.shares * self.price
...
class MyStock(Stock):
def cost(self):
# Check the call to `super`
actual_cost = super().cost()
return 1.25 * actual_cost
init 继承
如果__init__重新定义,则必须初始化父级。
class Stock:
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
class MyStock(Stock):
def __init__(self, name, shares, price, factor):
# Check the call to `super` and `__init__`
super().__init__(name, shares, price)
self.factor = factor
def cost(self):
return self.factor * super().cost()
3.多重继承
该类 Child 继承了父母双方的特征。
class Mother:
...
class Father:
...
class Child(Mother, Father):
...
通常来说我们并不这么做。
4.多态多态是编程中非常重要的概念。
它指的是使用单个类型实体(方法,运算符或对象)来表示不同场景中的不同类型。
多态是在继承的基础上组织相关对象。
class Shape:
...
class Circle(Shape):
...
class Rectangle(Shape):
...
5.魔法方法
python 的各个行为(方法)可以通过魔法方法定制,也称特殊方法。
类可以定义魔法方法,它们总是在方法名字之前和之后加上 __。
class Stock(object):
def __init__(self):
...
def __repr__(self):
...
数学运算类特殊方法:
a + b a.__add__(b) a - b a.__sub__(b) a * b a.__mul__(b) a / b a.__truediv__(b) a // b a.__floordiv__(b) a % b a.__mod__(b) a << b a.__lshift__(b) a >> b a.__rshift__(b) a & b a.__and__(b) a | b a.__or__(b) a ^ b a.__xor__(b) a ** b a.__pow__(b) -a a.__neg__() ~a a.__invert__() abs(a) a.__abs__()
容器类方法:
len(x) x.__len__() x[a] x.__getitem__(a) x[a] = v x.__setitem__(a,v) del x[a] x.__delitem__(a)
我们可以自定义这些方法:
class Sequence:
def __len__(self):
...
def __getitem__(self,a):
...
def __setitem__(self,a,v):
...
def __delitem__(self,a):
...
6.自定义异常类
自定义异常类总是继承自 Exception.
class NetworkError(Exception):
pass
还可以对异常进行层次结构排列。
class AuthenticationError(NetworkError):
pass
class ProtocolError(NetworkError):
pass
通常异常类为空类,用 pass填充。



