python第五十一课——__slots
生活随笔
收集整理的這篇文章主要介紹了
python第五十一课——__slots
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2.__slots__:
作用:限制對象隨意的動態(tài)添加屬性
舉例:
class Demo:
__slots__ = ('name','age','height','weight')
#實例化Demo對象
d = Demo()
#動態(tài)為d添加屬性
d.name = 'abc'
d.age = 12
#可以動態(tài)添加的屬性為:('name','age','height','weight')
#而sex不再范圍內(nèi),所以執(zhí)行代碼報錯了 --> AttributeError
# d.sex = '男'
print(d.name,d.age)
# print(d.sex)
演示__slots__屬性的使用: class Person:__slots__ = ('name','age','height','weight')pass#實例化Person對象 p=Person()#動態(tài)為對象添加屬性 p.name='tom' p.age=18 print(p.name,p.age)''' 以下代碼有問題:AttributeError... ''' print(p.__dict__)''' 嘗試為p對象動態(tài)添加sex屬性,但是sex并不是_slots_元組對象范圍內(nèi)的內(nèi)容, 所以不被允許,報錯:AttributeErro '''p.sex='男' print(p.sex)p.height=180.0 print(p.height)
轉(zhuǎn)載于:https://www.cnblogs.com/hankleo/p/10502521.html
總結(jié)
以上是生活随笔為你收集整理的python第五十一课——__slots的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javascript中的变量
- 下一篇: wamp解决ajax跨域问题