Python - __slots__

参考

  1. https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186739713011a09b63dcbd42cc87f907a778b3ac73000

概念

限制实例的属性, 比如,只允许对Student实例添加name和age属性。

class Student():

    # 用tuple定义允许绑定的属性名称
    __slots__ = ('name', 'age')

# 实例化Student
s1 = Student()
s1.name = 'allen'
s1.age = 22
s1.sex = 'male'  # AttributeError: 'Student' object has no attribute 'sex'

由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。

 __slots__定义的属性仅对当前类实例起作用;如果子类中没有__slots__,对继承的子类是不起作用

class Student():

    # 用tuple定义允许绑定的属性名称
    __slots__ = ('name', 'age')


class GraduateStudent(Student):
    pass

g = GraduateStudent()
g.score = 22    # it works

子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的_slots_

class Student():

    # 用tuple定义允许绑定的属性名称
    __slots__ = ('name', 'age')


class GraduateStudent(Student):

    __slots__ = ()

g = GraduateStudent()
g.score = 22    #AttributeError: 'GraduateStudent' object has no attribute 'score'

转载于:https://www.cnblogs.com/allen2333/p/9218984.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值