__slots__ magic method of Python class

In each class, instantiate an object will produce a dictionary to store all of an object's instance properties, so very useful, it allows us to set any new properties.

Every instance of an object python will allocate a fixed memory size dictionary to save the properties, if the object under many circumstances would be a waste of memory space.

By __slots__telling python Do not use the dictionary, but only to a fixed set of attributes of the allocated space

class Foo(object):
    __slots__ = ("x","y","z")

    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.z = None

    def tell_info(self,name):
      return  getattr(self,name)

c = Foo(10,20)
# 设置和获取__slots__中设置的可访问实例属性
print(c.tell_info("x"))      # 结果:10

c.z=50
print(c.tell_info("z"))  # 结果:50

# 设置一个不在__slots__中存在的属性,会报错
c.e = 70    # AttributeError: 'Foo' object has no attribute 'e'

# 访问对象.__dict__ 也会直接报错
print(c.__dict__) # AttributeError: 'Foo' object has no attribute '__dict__'

Guess you like

Origin blog.51cto.com/12643266/2432560