Python使用__slots__限制實例屬性

#定義一個類Student
class Student(object):
    __slots__ = ('name','age') #用元組(tuple)的形式綁定屬性名稱

s = Student()
s.name = 'xh'
print s.name  #xh

#s.score = 88  #由於 __slots__中沒有score屬性,因此報錯
#print s.score  #AttributeError: 'Student' object has no attribute 'score'

#定義一個類MidStudent繼承於Student
class MidStudent(Student):
    pass
m = MidStudent()
m.name = 'xm'
print m.name  #xm

#雖然父類對屬性進行了限制,但子類不受影響
m.score = 88
print m.score  #88
相關文章
相關標籤/搜索