一、MethodType()
>>> from types import MethodType
公共代码部分:
#!/usr/bin/python2.7 from types import MethodType #创建一个函数 def set_age(self, age): self.age=age #创建一个类 class Student(object): pass
将set_age方法绑定到对象上:
MethodType(set_age,s1,Student)
或MethodType(set_age,s1)
第一个参数是要绑定的方法,第二个参数是要绑定的对象,第三个参数是类名(可省略)s1=Student() s1.set_age=MethodType(set_age,s1,Student) s1.set_age(23) print s1.age #输出23 s2=Student() s2.set_age(24) print s2.age #报错,因为s2没有属性age
set_age
只是绑定在了s1
上,而不是绑定在Student
类上,所以这相当于s1
自己私有的。将
set_age
方法绑定到类上(没有None
参数):Student.set_age=MethodType(set_age,Student)
,不传入None
参数的时候,所有的实例会共用一份。Student.set_age=MethodType(set_age,Student) s1=Student() s2=Student() s1.set_age(20) s2.set_age(30) print s1.age # 输出30,而不是20 print s2.age # 输出30
将
set_age
方法绑定到类上(第二个参数为None
):Student.set_age=MethodType(set_age,None,Student)
,有参数None
时,set_age
就不是共享函数了,每个实例自有一份。Student.set_age=MethodType(set_age,None,Student) s1=Student() s2=Student() s1.set_age(20) s2.set_age(30) print s1.age #输出20 print s2.age #输出30
二、使用__slots__
在动态绑定属性时,达到加以限制的目的
class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
当某属性不在
__slots__
的tuple
中时,就不能被绑定,否则将得到AttributeError
的错误。>>> 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__
定义的属性仅对当前类实例起作用,对继承的子类是不起作用的。
除非在子类中也定义__slots__
,这样,子类实例允许定义的属性就是自身的__slots__
加上父类的__slots__
。
三、使用@property
相当于把一个私有属性的get或set函数合并成一个“假属性”来操作。
class Student(object):
@property def score(self): return self._score
@score.setter def score(self, value): if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value
_score
是类Student的一个私有属性,@property
下边是get方法,@score.setter
是set方法,设置好后,可以把score这个函数看做一个变量:
>>> s = Student()
>>> s.score = 60 # 实际转化为s.set_score(60)
>>> s.score # 实际转化为s.get_score()
60
>>> s.score = 9999
ValueError: score must between 0 ~ 100!
当不设置@score.setter
时,是个可读不可写的属性。
四、多重继承
通过多重继承,一个子类就可以同时获得多个父类的所有功能。
# -*- coding: utf-8 -*-
class Animal(object):
pass
class Friend(object):
pass
class Dog(Animal,Friend):
pass
MixIn: 一种设计模式(待补)
其它博客链接: