概述
class Foo(object): __slots__ = ['x'] def __init__(self,x=1): self.x = x # will the following work? def __setattr__(self,key,value): if key == 'x': object.__setattr__(self,name,-value) # Haha - let's set to minus x
我可以为它定义__setattr __()吗?
由于Foo没有__dict__,它会更新什么?
你不能做的是重新定义__setattr__以使用self .__ dict__,因为带槽的类的实例没有__dict__属性.但是这样的实例确实有一个self.x属性,它的内容只是没有存储在实例上的字典中.
相反,插槽值存储在__dict__实例字典将以其他方式存储的相同位置;在对象堆上.为len(__ slots__)引用保留空间,类上的descriptors代表您访问这些引用.
因此,在__setattr__钩子中,您可以直接调用这些描述符:
def __setattr__(self,value): if key == 'x': Foo.__dict__[key].__set__(self,-value)
有趣的绕道:是的,在没有__slots__属性的类上,有一个描述符可以让你访问实例的__dict__对象:
>>> class Bar(object): pass ... >>> Bar.__dict__['__dict__'] <attribute '__dict__' of 'Bar' objects> >>> Bar.__dict__['__dict__'].__get__(Bar(),Bar) {}
这是正常情况下如何查找自我.__ dict__.这让你想知道Bar .__ dict__对象的位置.在Python中,它是turtles all the way down,你当然会在类型对象上看到该对象:
>>> type.__dict__['__dict__'] <attribute '__dict__' of 'type' objects> >>> type.__dict__['__dict__'].__get__(Bar,type) dict_proxy({'__dict__': <attribute '__dict__' of 'Bar' objects>,'__module__': '__main__','__weakref__': <attribute '__weakref__' of 'Bar' objects>,'__doc__': None})
总结
以上是编程之家为你收集整理的python – 可以在__slots__类中定义__setattr __()吗?全部内容,希望文章能够帮你解决python – 可以在__slots__类中定义__setattr __()吗?所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧