加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 可以在__slots__类中定义__setattr __()吗?

发布时间:2020-12-16 23:39:24 所属栏目:Python 来源:网络整理
导读:假设我有一个定义__slots__的类: 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 m
假设我有一个定义__slots__的类:
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__,这正是没有你的__setattr__方法会发生的事情.所以简短的回答是:当然你可以定义一个__setattr__.

你不能做的是重新定义__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})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读