python __slots__ 详解(下篇)

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

from types import MethodType
class student(object):#先定义类student
    pass

s=student()
s.name='python' #动态给实例绑定一个属性
print 's.name=',s.name
def set_age(self,age):#定义一个函数(作为实例方法)
    self.age=age
s.set_age=MethodType(set_age,s,student)#给实例绑定一个方法    
s.set_age(26) #调用实例方法
print 's.age=',s.age  #测试结果
#注意:给一个实例绑定的变量和方法,对另一个实例不起作用
#为实例s绑定的变量name和方法set_age()对另一个实例s2不起作用
s2=student()
#print s2.name#AttributeError: 'student' object has no attribute 'name'   
#s2.set_age(23)#AttributeError: 'student' object has no attribute 'set_age' 
#若将变量和方法绑定到class上,则所有的实例均可访问
def set_score(self,score):#定义一个函数(绑定到类上)
    self.score=score
#绑定一个方法到class上,绑定之后,所有的实例均可调用
student.set_score=MethodType(set_score,None,student)
s.set_score(88)
s2.set_score(99)
print s.score,s2.score
运行结果:
s.name= python
s.age= 26
88 99
通常情况下,上面的set_score方法可以直接定义在class中,但动态绑定允许我们在程序运行的过程中动态给class加上功能,
这在静态语言中很难实现。
但是,如果我们想要限制class的属性怎么办?比如,只允许对student类的实例添加name和age属性。
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性,如下:

class student(object):  
    __slots__=('name','age')#用tuple定义允许绑定的属性名称       
  
s=student()#创建新的实例  
s.name='python'  
s.age=23  
print 's.name=',s.name,'s.age=',s.age  
#s.score=99 #AttributeError: 'student' object has no attribute 'score'     
''''' 
由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。 
使用__slots__要注意,__slots__定义的属性仅对当前类起作用,对其子类是不起作用的! 
也就是说,我们可以为子类实例动态绑定任意变量和方法 ,如下: 
'''  
class graduateStudent(student):  
    pass  
g=graduateStudent()  
print dir(g) #可以看到,实例g结构中包含__dict__属性,因此可以为实例g任意的添加属性!
g.score=99#动态给实例绑定一个属性  
print g.score  

运行结果:
s.name= python s.age= 23
['__class__', '__delattr__', ' __dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']
99
如果父类和子类中都定义__slots__,这样,子类允许定义的属性就是 自身的__slots__加上父类的__slots__。如下:

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

class graduateStudent(student):
    __slots__=('x','y')

g=graduateStudent()
#子类允许定义的属性就是自身的__slots__加上父类的__slots__
g.name='python'
g.age=23
g.x=11
g.y=33
print g.name,g.age,g.x,g.y
#g.score=100 #AttributeError: 'graduateStudent' object has no attribute 'score'
运行结果:
python 23 11 33

class A(object):
    pass
class B(A):
    __slots__=('x')
    
print dir(A)#可以看到A类有一个__dict__属性
print dir(B)#B类也有一个__dict__属性(继承了父类A中的__dict__属性)  
b=B()
b.x=9
print 'b.x=',b.x
b.y=8 #B类包含了__dict__属性,其实例可以任意添加属性
print 'b.y=',b.y
运行结果:
['__class__', '__delattr__', ' __dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
['__class__', '__delattr__', ' __dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', 'x']
b.x= 9
b.y= 8

class A(int):
    __slots__=('x')


print dir(int)#可以看到,int类不包含__dict__属性(python中的内建类型不包含__dict__属性)
print dir(A)#A类也不包含__dict__属性,但包含__slots__属性(因此A类的实例可以添加的属性局限于__slots__)
a=A()
a.x=78
print 'a.x=',a.x
#a.y=98 #AttributeError: 'A' object has no attribute 'y'
运行结果:
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__module__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', ' __slots__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real', 'x']
a.x= 78
综上所述:
如果 父类存在__dict__属性,则其子类将继承__dict__;此时,即使该子类包含了__slots__属性, 该子类的实例依然可以任意添加变量


(完)




  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值