python __slot__的使用

1、不使用__slots__

class MyClass(object):

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

obj = MyClass('jack', 123)
obj.k = 456
print(obj.k)

  默认情况下Python用一个字典来保存一个对象的实例属性。这非常有用,因为它允许我们在运行时去设置任意的新属性。

2、使用__slots__

class MyClass(object):
    __slots__ = ['name', 'identifier']
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier

obj = MyClass('jack', 123)
obj.k = 456
print(obj.k)

  执行时产生错误:

AttributeError: 'MyClass' object has no attribute 'k'

  具体参见:https://blog.csdn.net/qq_35636311/article/details/78248491

猜你喜欢

转载自www.cnblogs.com/bad-robot/p/9851544.html
今日推荐