python编程:__slots__限制class的属性

__slots__限制class的属性

# 代码示例

# -*- 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'

猜你喜欢

转载自blog.csdn.net/mouday/article/details/80492859
今日推荐