一、使用__slots__
- 正常情况下,当我们定义了一个
类
,并且根据类
创建了实例
后,我们可以给这些实例绑定任何属性和方法
,就这是动态语言的灵活性,下面来看案例:
- 创建一个类 >>> class Student(object): ... pass ... - 创建一个实例,并且绑定属性'name' >>> zhangsan = Student() >>> zhangsan.name = 'zhangsan' >>> zhangsan.name 'zhangsan' - 还可以绑定方法 >>> def set_age(self,age): ... self.age = age ... >>> from types import MethodType #导入模块 >>> zhangsan.set_age = MethodType(set_age,zhangsan) #给zhangsan实例绑定方法 >>> zhangsan.set_age(22) >>> zhangsan.age 22 - 上面的'zhangsan'实例绑定的方法,只对'zhangsan'本身生效,如果根据'Student'类再次创建实例,'新创建的实例是没有这些方法的' >>> lisi = Student() >>> lisi.set_age Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'set_age' >>> lisi.set_age(33) #无法调用 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'set_age' - 如果想让上面的方法绑定到所有根据'Student'类创建的实例,我们可以直接给'Student类'绑定方法 >>> def set_score(self,score): ... self.score = score ... >>> Student.set_score = set_score >>> lisi.set_score(99) >>> lisi.score 99 >>> zhangsan.set_score(98) >>> zhangsan.score 98
通常情况下,上面的set_score方法是可以直接定义到类中的,但是动态绑定允许我们在程序运行的过程中动态的为类添加功能,这在静态语言中很难实现
当我们需要限制实例的属性,例如,只允许对Student类创建的实例添加name和age属性,想要达到这种效果,我们可以在定义类的时候,定义一个特殊的__slots__变量,来限制实例可添加的属性:
- 可以看到在使用'__slots__'变量后,创建的实例'zhangsan'只可以绑定特点的属性 >>> class Student(object): ... __slots__ = ('name','age') ... >>> zhangsan = Student() >>> zhangsan.name = 'zhangsan' >>> zhangsan.age = 22 >>> zhangsan.score = 98 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'score' - 要注意的是,类中的'__slots__'变量'只对当前类的实例有效,对继承的子类是无效的' >>> class Test_Student(Student): ... pass ... >>> lisi = Test_Student() >>> lisi.score = 98 >>> lisi.score 98
注意:在类中的__slots__变量只对当前类创建的实例有效,对继承的子类是无效的
二、使用装饰器——@property
在绑定属性时,如果直接把属性暴露出去,这样虽然写起来简单,但是无法检查参数,导致可以随意修改属性,例如:
>>> class Student(object): ... pass ... >>> zhangsan = Student() >>> zhangsan.score = 98 >>> zhangsan.score 98
可以看到,上面的zhangsan实例的score属性是可以随意定义、修改的,在实际环境中,肯定不允许这样随意进行定义、修改,为了限制score属性的范围,我们可以在类中通过添加set_score()方法来限制score属性,然后再添加一个get_score()方法来获取score,这种方式在之前的私有变量中提到过,下面来看案例:
- 在类中使用if语句进行判断,限制score属性,可以看到在根据类创建实例后,实例的'score'属性无法随意定义、修改了 >>> class Student(object): ... def get_score(self): ... return self.score ... def set_score(self,value): ... if not isinstance(value,int): #使用isinstance判断传入参数value的类型是否为int类型 ... raise ValueError('score not is int') #使用raise抛出异常 ... if value < 0 or value > 100: ... raise ValueError('score must between 0 — 100!!') ... self.score = value ... >>> zhangsan = Student() >>> zhangsan.set_score('98') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in set_score ValueError: score not is int >>> zhangsan.set_score(120) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 8, in set_score ValueError: score must between 0 — 100!! >>> zhangsan.set_score(98) >>> zhangsan.score 98
虽然上面创建类的方式可以实现效果,但是调用方法略显复杂,没有直接使用属性那么简单
之前有说过装饰器这个概念,装饰器可以动态的给函数添加功能,而在Python中,对于类的方法,装饰器一样有效,Python内置的@property装饰器就是负责把一个方法变成属性进行调用
- '@property'的实现比较复杂,来看下面的'Student'类,想要把一个'获取属性的方法'变成属性,只需要加上'@property'即可,而在下面,还可以看到'@property.setter',这是创建的另一个装饰器,负责把一个'赋值属性的方法'变成属性,于是,我们就有拥有了一个可控的属性操作 >>> class Student(object): ... @property ... def score(self): ... return self._score ... @score.setter ... def score(self,value): ... if not isinstance(value,int): ... raise ValueError('score not is int!') ... if value < 0 or value > 100: ... raise ValueError('score must between 0 - 100!!') ... self._score = value ... >>> zhangsan = Student() >>> zhangsan.score = 98 #进行赋值操作,实际调用的是第二个score方法,也就是zhangsan.set_score(98)这样的 >>> zhangsan.score #同样的,进行获取操作,实际调用的是第一个score方法,也就是zhangsan.get_score()这样的 98 >>> zhangsan.score = '98' #可以看到在赋值时不符合属性要求会报错 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 8, in score ValueError: score not is int! >>> zhangsan.score = 120 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 10, in score ValueError: score must between 0 - 100!!
上面的代码中,单独的@property其实就是getter方法,并且是只读属性的,例如:
- 下面只使用了'getter'的装饰器,可以看到,除了在创建实例的时候可以传入'self._age'的值,创建后直接修改'zhangsan'的'age'属性值会报错,这就是'只读属性' >>> class Student(object): ... def __init__(self,age): ... self._age = age ... @property ... def age(self): ... return print(self._age) ... >>> zhangsan = Student(22) >>> zhangsan.age 22 >>> zhangsan.age = 25 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: can't set attribute 'age'
- 而上面代码中的
@score.setter
其实就是setter
方法,也就是用来修改属性的值的,例如:
- 可以看到在使用'@age.setter'后,可以随意的去修改'self._age'的值 >>> class Student(object): ... @property ... def age(self): ... return print(self._age) ... @age.setter ... def age(self,value): ... self._age = value ... >>> zhangsan = Student() >>> zhangsan.age = 22 >>> zhangsan.age 22 >>> zhangsan.age = 25 >>> zhangsan.age 25
注意:
要特别注意的是,
属性的方法名千万不要和实例变量重名
,否则会造成无限递归,导致栈溢出报错,例如:
>>> class Student(object): ... @property ... def age(self): ... return print(self._age) #这里设置为self._age,就是因为如果不加下划线,那么变量就跟方法名冲突了 ... @age.setter ... def age(self,value): ... self._age = value
- 其实这个上面装饰器达到的效果可以添加多个方法来实现,例如添加
get_age
和set_age
等,但是最终调用的是方法,如zhangsan.get_age()
,而使用装饰器后,可以看到调用的是属性zhangsan.age
三、多重继承(多继承)
- 在之前说面向对象编程时,说到过三大基本特性之一的
继承
特性,继承是面向对象编程的一个重要方式,因为通过继承,子类就可以继承并扩展父类的功能
,而一个类是可以继承多个父类的,这种继承就叫做多重继承,也就是多继承,下面来看一个案例,理解多继承的作用:
- 假如我们要实现以下四种动物:
Dog——狗
Bat——蝙蝠
Parrot——鹦鹉
Ostrich——鸵鸟
首先可以根据特性进行分类,例如通过哺乳动物和鸟类动物,可以这样分:
而如果通过“能跑”和“能飞”来说,可以这样分:
如果在分的细点,就需要设置更多的层次,例如,哺乳动物中能飞能跑的,鸟类中能飞能跑的
如果还要增加“宠物类”和“非宠物类”的话,类的数量会呈指数增长,这样明显是不行的,正确的做法就是使用多重继承,通过多重继承,一个子类就可以同时获得多个父类的所有功能,例如:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #最上层的Animal类 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
下面,我们要给动物加上各种功能,例如:
- 添加跑和飞的类 #!/usr/bin/env python3 # -*- coding: utf-8 -*- #添加跑和飞的类 class Runnable(object): def run(self): return print('Running...') class Flyable(object): def fly(self): return print('Flying...') #最上层的Animal类 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
可以利用多重继承的特性让动物继承多个类,例如:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #添加跑和飞的类 class Runnable(object): def run(self): return print('Running...') class Flyable(object): def fly(self): return print('Flying...') #最上层的Animal类 class Animal(object): pass #第二层的哺乳动物和鸟类 class Mammal(Animal): pass class Bird(Animal): pass #第三层的各种动物 class Dog(Mammal,Runnable): pass class Bat(Mammal,Flyable): pass class Parrot(Bird,Flyable): pass class Ostrich(Bird,Runnable): pass
多重继承这种让类继承多个类的设计,也叫做Mixln,是一种常见设置,只允许单一继承的语言,例如java是不能使用Mixln设计的