當我們通過一個類建立了執行個體之後,仍然可以給執行個體添加屬性,但是這些屬性只屬於這個執行個體。有些時候,我們可以需要限制類執行個體對象的屬性,這時就要用到類中的_ _slots _ _ 屬性了。_ _ slots_ _屬性對於一個tuple,只有這個tuple中出現的屬性可以被類執行個體使用。
class person(object): __slots__ = ("name", "age","weight") def __init__(self, name, age, weight): self.name = name self.age = age self.weight = weightBruce = person("Bruce", 25,60) print("%s is %d years old and he weights %s" %(Bruce.name, Bruce.age,Bruce.weight))Bruce.tall = 180
Bruce is 25 years old and he weights 60
---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-45-6d049f8dbc1b> in <module>() 7 Bruce = person("Bruce", 25,60) 8 print("%s is %d years old and he weights %s" %(Bruce.name, Bruce.age,Bruce.weight))----> 9 Bruce.tall = 180AttributeError: 'person' object has no attribute 'tall'
person類執行個體化後,Bruce不能添加新的屬性,_ _ slots_ _屬性對於一個tuple屬性賦值,只有這個tuple中出現的屬性可以被類執行個體使用 使用_ _ slots _ _ 要注意, _ _ slots_ _定義的屬性僅對當前類的執行個體起作用,對繼承的子類執行個體是不起作用的,不會限制繼承的子類執行個體化再添加新的屬性
class human(object): __slots__ = ("name", "age","weight")class person(human): #__slots__ = ("name", "age","weight") def __init__(self, name, age, weight): self.name = name self.age = age self.weight = weightBruce = person("Bruce", 25,60) print("%s is %d years old and he weights %s" %(Bruce.name, Bruce.age,Bruce.weight))Bruce.tall = 180
Bruce is 25 years old and he weights 60
如果子類本身也有_ _ slots_ _ 屬性,子類的屬性就是自身的 _ _ slots _ _ 加上父類的_ _ slots_ _
class human(object): __slots__ = ("tall")class person(human): __slots__ = ("name", "age","weight") def __init__(self, name, age, weight): self.name = name self.age = age self.weight = weightBruce = person("Bruce", 25,60) print("%s is %d years old and he weights %s" %(Bruce.name, Bruce.age,Bruce.weight))Bruce.tall = 180print("%s is %d years old and he weights %s and he\'s tall is %s" %(Bruce.name, Bruce.age,Bruce.weight,Bruce.tall))Bruce.appearance = 'handsome'
Bruce is 25 years old and he weights 60Bruce is 25 years old and he weights 60 and he's tall is 180
---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-49-617f9b7100f2> in <module>() 12 Bruce.tall = 180 13 print("%s is %d years old and he weights %s and he\'s tall is %s" %(Bruce.name, Bruce.age,Bruce.weight,Bruce.tall))---> 14 Bruce.appearance = 'o,no'AttributeError: 'person' object has no attribute 'appearance'
父類 和 子類 限制的 元組裡面的變數屬性都是可以產生調用 的。appearance 既不在父類也不再繼承的子類 的元組列表裡, 不能產生