当我们通过一个类创建了实例之后,仍然可以给实例添加属性,但是这些属性只属于这个实例。有些时候,我们可以需要限制类实例对象的属性,这时就要用到类中的_ _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 = weight
Bruce = 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)in () 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 = 180 AttributeError: 'person' object has no attribute 'tall'
person类实例化后,Bruce不能添加新的属性,_ _ slots_ _属性对于一个tuple属性赋值,只有这个tuple中出现的属性可以被类实例使用
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 = weight
Bruce = 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
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 = weight
Bruce = person("Bruce", 25,60)
print("%s is %d years old and he weights %s" %(Bruce.name, Bruce.age,Bruce.weight))
Bruce.tall = 180
print("%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 60 Bruce is 25 years old and he weights 60 and he's tall is 180
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last)in () 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'