< 笔记 > Python - 08 Python 面向对象高级编程(OOP Advanced Features)

08 Python 面向对象高级编程(OOP Advanced Features)

By Kevin Song

  • 08-01 __slots__
  • 08-02 @property
  • 08-03 多重继承
  • 08-04 定制类
  • 08-05 枚举类
  • 08-06 元类

08-01 __slots__

给对象绑定属性和方法

class Student(object):
    pass

给对象绑定属性

>>> s = Student()
>>> s.name = 'Kevin' # 动态给实例绑定一个属性
>>> print(s.name)
Kevin

给对象绑定方法

>>> def set_age(self, age): # 定义一个函数作为实例方法
...     self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25

给实例绑定方法,对另一个实例不起作用

>>> s2 = Student() # 创建新的实例
>>> s2.set_age(25) # 尝试调用方法
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'set_age'

给class绑定方法,所有实例都可用

>>> def set_score(self, score):
...     self.score = score
...
>>> Student.set_score = set_score
>>> s.set_score(100)
>>> s.score
100
>>> s2.set_score(99)
>>> s2.score
99

限制给对象绑定属性和方法

定义class的时候,定义一个特殊的 __slots__ 变量,来限制该class实例能添加的属性

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称

只能绑定name和age

>>> s = Student() # 创建新的实例
>>> s.name = 'Michael' # 绑定属性'name'
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

注意: __slots__定义的属性仅对当前类实例起作用,对继承的子类不起作用

>>> class GraduateStudent(Student):
...     pass
...
>>> g = GraduateStudent()
>>> g.score = 9999

08-02 @property

直接修改属性,因为可以直接修改,所以不符合逻辑

s = Student()
s.score = 9999

为了限制score范围,可以用 set_score() 方法设置成绩,用 get_score() 获取成绩

class Student(object):

    def get_score(self):
         return self._score

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
>>> s = Student()
>>> s.set_score(60) # ok!
>>> s.get_score()
60
>>> s.set_score(9999)
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

上面的调用方法略显复杂,没有直接用属性这么直接简单,所以用 @property 装饰器把 方法 变成属性

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
  • @property:把一个getter方法变成属性
  • @score.setter:把一个setter方法变成属性
>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:

class Student(object):

    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self, value):
        self._birth = value

    @property
    def age(self):
        return 2015 - self._birth

08-03 多重继承

class Animal(object):
    pass

# 大类:
class Mammal(Animal):
    pass

class Bird(Animal):
    pass

# 各种动物:
class Dog(Mammal):
    pass

class Bat(Mammal):
    pass

class Parrot(Bird):
    pass

class Ostrich(Bird):
    pass

定义好Runnable和Flyable的类

class Runnable(object):
    def run(self):
        print('Running...')

class Flyable(object):
    def fly(self):
        print('Flying...')

给Dog加上Runnable,给Bat加上Flyable

class Dog(Mammal, Runnable):
    pass
class Bat(Mammal, Flyable):
    pass

MixIn

为了更好地看出继承关系:RunnableFlyable 改为 RunnableMixInFlyableMixIn

class Dog(Mammal, RunnableMixIn, CarnivorousMixIn):
    pass

08-04 定制类

输出自定义信息:__str__ 和 __repr__()

打印自定义信息:__str__

定义Student类,打印实例

>>> class Student(object):
...     def __init__(self, name):
...         self.name = name
...
>>> print(Student('Michael'))
<__main__.Student object at 0x109afb190>

__str__ 打印自定义实例信息

>>> class Student(object):
...     def __init__(self, name):
...         self.name = name
...     def __str__(self):
...         return 'Student object (name: %s)' % self.name
...
>>> print(Student('Michael'))
Student object (name: Michael)
直接显示变量自定义信息:__repr__()
>>> class Student(object):
...     def __init__(self, name):
...         self.name = name
...     def __str__(self):
...         return 'Student object (name: %s)' % self.name
...     __repr__ = __str__
...
>>> s = Student('Michael')
>>> s
Student object (name: Michael)

__iter__

如果一个类想被用于for … in循环,类似list或tuple那样,就必须实现一个iter()方法,该方法返回一个迭代对象

for循环就会不断调用该迭代对象的next()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环

class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1 # 初始化两个计数器a,b

    def __iter__(self):
        return self # 实例本身就是迭代对象,故返回自己

    def __next__(self):
        self.a, self.b = self.b, self.a + self.b # 计算下一个值
        if self.a > 100000: # 退出循环的条件
            raise StopIteration()
        return self.a # 返回下一个值

__getattr__

调用类的方法或属性时,如果不存在,就会报错

class Student(object):

    def __init__(self):
        self.name = 'Michael'
>>> s = Student()
>>> print(s.name)
Michael
>>> print(s.score)
Traceback (most recent call last):
  ...
AttributeError: 'Student' object has no attribute 'score'

要避免这个错误,写一个getattr()方法,动态返回一个属性

class Student(object):

    def __init__(self):
        self.name = 'Michael'

    def __getattr__(self, attr):
        if attr=='score':
            return 99

当调用不存在的属性时,比如score,Python解释器会试图调用getattr(self, ‘score’)来尝试获得属性

>>> s = Student()
>>> s.name
'Michael'
>>> s.score
99

注意: 只有在没有找到属性的情况下,才调用getattr,已有的属性,比如name,不会在getattr中查找

返回函数也完全可以

class Student(object):

    def __getattr__(self, attr):
        if attr=='age':
            return lambda: 25
>>> s.age()
25

__call__

直接对实例进行调用

class Student(object):
    def __init__(self, name):
        self.name = name

    def __call__(self):
        print('My name is %s.' % self.name)
>>> s = Student('Kevin')
>>> s() # self参数不要传入
My name is Kevin.

判断一个对象是否能被调用(是否是Callable对象)

>>> callable(Student())
True
>>> callable(max)
True
>>> callable([1, 2, 3])
False
>>> callable(None)
False
>>> callable('str')
False

08-05 枚举类

用大写变量定义的常量任然是变量

JAN = 1
FEB = 2
MAR = 3

解决方案:Enum类(为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例)

from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

直接使用Month.Jan来引用一个常量

>>> Month.Jan
<Month.Jan: 1>

枚举所有成员

>>> for name, member in Month.__members__.items():
...     print(name, '=>', member, ',', member.value)
... 
Jan => Month.Jan , 1
Feb => Month.Feb , 2
Mar => Month.Mar , 3
Apr => Month.Apr , 4
May => Month.May , 5
Jun => Month.Jun , 6
Jul => Month.Jul , 7
Aug => Month.Aug , 8
Sep => Month.Sep , 9
Oct => Month.Oct , 10
Nov => Month.Nov , 11
Dec => Month.Dec , 12
>>> 

更精确地控制枚举类型,可以从Enum派生出自定义类

from enum import Enum, unique

@unique
class Weekday(Enum):
    Sun = 0 # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

@unique装饰器可以帮助我们检查保证没有重复值

访问这些枚举类型可以有若干种方法

>>> day1 = Weekday.Mon
>>> print(day1)
Weekday.Mon
>>> print(Weekday.Tue)
Weekday.Tue
>>> print(Weekday['Tue'])
Weekday.Tue
>>> print(Weekday.Tue.value)
2
>>> print(day1 == Weekday.Mon)
True
>>> print(day1 == Weekday.Tue)
False
>>> print(Weekday(1))
Weekday.Mon
>>> print(day1 == Weekday(1))
True
>>> Weekday(7)
Traceback (most recent call last):
  ...
ValueError: 7 is not a valid Weekday
>>> for name, member in Weekday.__members__.items():
...     print(name, '=>', member)
...
Sun => Weekday.Sun
Mon => Weekday.Mon
Tue => Weekday.Tue
Wed => Weekday.Wed
Thu => Weekday.Thu
Fri => Weekday.Fri
Sat => Weekday.Sat

08-06 元类

type()

作用一: 查看一个类型或变量的类型

定义一个Hello的class

class Hello(object):
    def hello(self, name='world'):
        print('Hello, %s.' % name)
>>> from hello import Hello
>>> h = Hello()
>>> h.hello()
Hello, world.
>>> print(type(Hello))
<class 'type'>
>>> print(type(h))
<class 'hello.Hello'>
  • Hello是一个class,它的类型就是type
  • h是一个实例,它的类型就是class Hello

作用二: 创建一个class对象

  • type()函数依次传入3个参数
    1. class的名称
    2. 继承的父类集合(Python支持多重继承,如果只有一个父类,需要用tuple的单元素写法)
    3. class的方法名称与函数绑定
>>> def fn(self, name='world'): # 先定义函数
...     print('Hello, %s.' % name)
...
>>> Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class
>>> h = Hello()
>>> h.hello()
Hello, world.
>>> print(type(Hello))
<class 'type'>
>>> print(type(h))
<class '__main__.Hello'>

元类(metaclass)

定义:类的类(类看做元类的实例)
作用:控制类的创建行为

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值