Python基础(__slots__)

class Point(object):
    __slots__ = ('name','point')
p1 = Point()
p1.name = 100
print(p1.name)#100
#p1.score = 200#由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误

#使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
#除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__
class PointExtend(Point):
    pass
p2 = PointExtend
p2.score = 200
print(p2.score)#200

 

posted @ 2019-05-20 08:46  周大侠小课堂  阅读(169)  评论(0编辑  收藏  举报