Python面向对象编程(二)

本文我们继续介绍一些Python面向对象编程中的高级用法,依然参考廖雪峰老师的Python教程。

教程地址:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186739713011a09b63dcbd42cc87f907a778b3ac73000

1、使用__slots__

正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性,看下面的例子:

class Animal():
    pass

ani = Animal()
ani.name = 'hasky'

from types import MethodType
def set_age(self,age):
    self.age = age

ani.set_age = MethodType(set_age,ani)
ani.set_age(20)
print(ani.age) #20 

可以看到,我们可以直接通过赋值的方式给实例绑定属性,同时可以通过MethodType方法给实例绑定方法。值得注意的是,给一个实例绑定的属性和方法,对另一个实例是不起作用的。都会报AttributeError。

ani2 = Animal()
print(ani2.name) # AttributeError: 'Animal' object has no attribute 'name'
ani2.set_age(20) # AttributeError: 'Animal' object has no attribute 'set_age'

为了给所有实例都绑定方法,那么我们给class绑定方法:

Animal.set_age = set_age
ani2.set_age(20)
print(ani2.age) # 20

但是,如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加name和age属性。

为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:

class Animal():
    __slots__ = ['name','weight']
    
ani = Animal()
ani.name = 'hasky'
ani.weight = 90
ani.height = 20 # AttributeError: 'Animal' object has no attribute 'height'

可以看到,由于height没有在__slots__中,所以无法给实例绑定该属性,报 AttributeError。

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

class Dog(Animal):
    pass
dog = Dog()
dog.height = 20
print(dog.height) # 20

2、使用@property

在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把属性值随便改,为了避免这样的情况,我们可以使用getter和setter来限制对属性值的修改,比如我们将动物的体重限制1到200之间的整数。

class Animal(object):

    def get_weight(self):
         return self.weight

    def set_weight(self, value):
        if not isinstance(value, int):
            raise ValueError('weight must be an integer!')
        if value < 1 or value > 200:
            raise ValueError('weight must between 1 ~ 200!')
        self.weight = value
ani = Animal()
ani.set_weight(60)
print(ani.get_weight()) # 60
ani.set_weight(999) # ValueError: weight must between 1 ~ 200!

但是上面的调用方法太复杂,没有直接用属性这么简单,我们可以使用Python内置的@property装饰器来把一个方法变成属性调用:

class Animal(object):
    @property
    def weight(self):
         return self._weight
        
    @weight.setter
    def weight(self, value):
        if not isinstance(value, int):
            raise ValueError('weight must be an integer!')
        if value < 1 or value > 200:
            raise ValueError('weight must between 1 ~ 200!')
        self._weight = value
        
ani = Animal()
ani.weight = 60
print(ani.weight) # 60
ani.weight = 999 #  ValueError: weight must between 1 ~ 200!

上面的代码中,注意的一点是,由于我们的方法名已经是weight了
,所以属性的名称不能再是weight,我们使用的是_weight。把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@weight.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作。

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

class Animal(object):
    @property
    def birth(self):
         return self._birth
        
    @birth.setter
    def birth(self, value):
        if not isinstance(value, int):
            raise ValueError('birth must be an integer!')
        if value < 1 or value > 2018:
            raise ValueError('birth must between 1 ~ 2018!')
        self._birth = value
    
    @property
    def age(self):
        return 2018 - self._birth
        
ani = Animal()
ani.birth = 1958
print(ani.age) # 60

3、定制类

看到形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的。比如我们刚刚介绍的__slots__用于限制实例绑定属性。除此之外,Python的class中还有许多这样有特殊用途的函数,可以帮助我们定制类。

3.1 __str__

对于一个实例,我们直接打印的话,往往是下面的结果:

print(ani) # <__main__.Animal object at 0x104fccd68>

我们如何把打印结果变的好看一些呢?__str__就派上用场了。

class Animal(object):
    def __init__(self,name):
        self.name = name
    def __str__(self):
        return 'Animal object with name : %s' % self.name
print(Animal('tt')) # Animal object with name : tt
a = Animal('tt')
a # <__main__.Animal at 0x104e8ecf8>

可是,如果我们不用print而是直接敲变量,打印出来的结果还是不好看,这是因为直接显示变量调用的不是__str__(),而是__repr__(),两者的区别是__str__()返回用户看到的字符串,而__repr__()返回程序开发者看到的字符串,也就是说,__repr__()是为调试服务的。我们只需要在类中增加一行__repr__ =__str__就可以让直接敲变量打印出来的结果好看一些。

3.2 __iter__

如果一个类想被用于for … in循环,类似list或tuple那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象,然后,Python的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 > 10: # 退出循环的条件
            raise StopIteration()
        return self.a # 返回下一个值
for n in Fib():
    print(n)

这样,我们的输出为:

《Python面向对象编程(二)》

3.3 __getitem__

使用__iter__()和__next__()虽然可以让实例进行循环,但是并不能当作一个list来使用,比如想要获取其中的某个元素或者进行切片操作。要表现得像list那样按照下标取出元素,需要实现__getitem__()方法。同时,__getitem__()传入的参数可能是一个int,也可能是一个切片对象slice,可以获得一个指定的元素或者一堆连续的元素:

class Fib(object):
    def __getitem__(self, n):
        if isinstance(n, int): # n是索引
            a, b = 1, 1
            for x in range(n):
                a, b = b, a + b
            return a
        if isinstance(n, slice): # n是切片
            start = n.start
            stop = n.stop
            if start is None:
                start = 0
            a, b = 1, 1
            L = []
            for x in range(stop):
                if x >= start:
                    L.append(a)
                a, b = b, a + b
            return L
f = Fib()
print(f[0:5]) # [1, 1, 2, 3, 5]
print(f[10]) # 89

3.4 __getattr__

正常情况下,当我们调用类的方法或属性时,如果不存在,就会报错。比如我们访问一个不存在的height属性,就会报AttributeError。解决这个问题的方法一个是在类中加入一个height属性,另一个就是写一个__getattr__()方法,动态返回一个属性:

class Animal():
    def __init__(self,name,weight):
        self.name = name
        self.weight = weight
    def __getattr__(self,attr):
        if attr == 'height':
            return 20
a = Animal("hasky",90)
print(a.height) # 20

上面的代码中,当调用不存在的属性时height时,Python解释器会试图调用__getattr__(self, ‘height’)来尝试获得属性,这样,我们就有机会返回height的值。除了返回属性外,返回函数也是可以的:

class Animal():
    def __init__(self,name,weight):
        self.name = name
        self.weight = weight
    def __getattr__(self,attr):
        if attr == 'height':
            return 20
        elif attr == 'age':
            return lambda: 25
a = Animal("hasky",90)
print(a.height) # 20
print(a.age()) # 25

注意,只有在没有找到属性的情况下,才调用__getattr__,已有的属性,比如name,不会在__getattr__中查找。同时,如果定义了__getattr__方法,那么对于不存在的属性,不会报错,而是会统一返回None:

class Animal():
    def __init__(self,name,weight):
        self.name = name
        self.weight = weight
    def __getattr__(self,attr):
        if attr == 'height':
            return 20
        elif attr == 'age':
            return lambda: 25
a = Animal("hasky",90)
print(a.abc) # None

为了,让程序抛出AttributeError的错误,我们需要对__getattr__()进行修改:

class Animal():
    def __init__(self,name,weight):
        self.name = name
        self.weight = weight
    def __getattr__(self,attr):
        if attr == 'height':
            return 20
        elif attr == 'age':
            return lambda: 25
        raise AttributeError('Animal object has no attribute %s' % attr)
a = Animal("hasky",90)
print(a.abc) # AttributeError: Animal object has no attribute abc
    原文作者:石晓文的学习日记
    原文地址: https://www.jianshu.com/p/9e996c9b709d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞