您当前的位置: 首页 >  Python

python编程:__slots__限制class的属性

彭世瑜 发布时间:2018-05-29 10:26:32 ,浏览量:4

__slots__限制class的属性

__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的

代码示例
# -*- coding: utf-8 -*-

# @File    : slots_demo.py
# @Date    : 2018-05-29

class Dog(object):
    def __init__(self, name):
        self.name = name


class Cat(object):
    __slots__ = ["name"]

    def __init__(self, name):
        self.name = name


if __name__ == '__main__':
    d = Dog("dog")
    d.age = 23
    print(d.age)
    # 23

    c = Cat("cat")
    c.age = 24
    # AttributeError: 'Cat' object has no attribute 'age'
关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 4浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.1175s