python 类与对象 __slots__的使用

#使用__slots__"
class Student(object):
    pass

s = Student()
s.name = 'Michael' #动态给实例绑定一个属性
print(s.name)
Michael
#给实例绑定一个方法
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)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-17-c8243b1832b5> in <module>
      1 s2 = Student()
----> 2 s2.set_age(25)


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(90)
s2.score
90
但是我们要限制实例属性该怎么办?比如只允许添加name和age属性
#这里引入__slots__来限制属性
class Student1(object):
    __slots__ = ('name','age') #用tuple定义允许绑定的属性名称
s3 = Student1()
s3.name ='Michael'
s3.age = 25
s3.score = 88
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-24-2069d6e5cbf8> in <module>
      2 s3.name ='Michael'
      3 s3.age = 25
----> 4 s3.score = 88


AttributeError: 'Student1' object has no attribute 'score'
由于’score’没有放到__slots__中,所以不能绑定score属性
注意:__slots__定义的属性仅对当前类的实例起作用,对继承的子类是不起作用的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值