如何在覆盖其类上的 __dict__ 属性后访问实例字典?

Ash*_*ary 1 python class python-internals

考虑这个例子,其中__dict__类的所有实例的 都A将指向全局 dict shared

shared = {'a': 1, 'b': 2}

class A(object):
    def __init__(self):
        self.__dict__ = shared
Run Code Online (Sandbox Code Playgroud)

现在让我们测试一些事情:

>>> a = A()
>>> b = A()
>>> a.a, a.b, b.a, b.b
(1, 2, 1, 2)
>>> b.x = 100
>>> shared
{'a': 1, 'x': 100, 'b': 2}
>>> a.x
100
>>> c = A()
>>> c.a, c.b, c.x
(1, 2, 100)
>>> shared['foo'] = 'bar'
>>> a.foo, b.foo, c.foo
('bar', 'bar', 'bar')
>>> a.__dict__, b.__dict__, c.__dict__
({'a': 1, 'x': 100, 'b': 2, 'foo': 'bar'},
 {'a': 1, 'x': 100, 'b': 2, 'foo': 'bar'},
 {'a': 1, 'x': 100, 'b': 2, 'foo': 'bar'}
)
Run Code Online (Sandbox Code Playgroud)

一切都按预期进行。


现在让我们A通过添加名为 的属性来稍微调整类__dict__

shared = {'a': 1, 'b': 2}

class A(object):
    __dict__ = None
    def __init__(self):
        self.__dict__ = shared
Run Code Online (Sandbox Code Playgroud)

让我们再次运行同一组步骤:

>>> a = A()
>>> b = A()
>>> a.a, a.b, b.a, b.b
AttributeError: 'A' object has no attribute 'a'
>>> b.x = 100
>>> shared
{'a': 1, 'b': 2}
>>> b.__dict__  # What happened to x?
{'a': 1, 'b': 2}
>>> a.x
AttributeError: 'A' object has no attribute 'x'
>>> c = A()
>>> c.a, c.b, c.x
AttributeError: 'A' object has no attribute 'a'
>>> shared['foo'] = 'bar'
>>> a.foo, b.foo, c.foo
AttributeError: 'A' object has no attribute 'foo'
>>> a.__dict__, b.__dict__, c.__dict__
({'a': 1, 'b': 2, 'foo': 'bar'},
 {'a': 1, 'b': 2, 'foo': 'bar'},
 {'a': 1, 'b': 2, 'foo': 'bar'}
)
>>> b.x  # Where did this come from?
100
Run Code Online (Sandbox Code Playgroud)

根据上述信息,第一个案例按预期工作,但第二个案例没有,因此我想知道添加类级别__dict__属性后发生了什么变化。我们可以以任何方式访问现在正在使用的实例字典吗?

Ash*_*ary 5

在第一种情况下,self.__dict__可以访问__dict__其类型提供的描述符。该描述符允许它获取底层实例字典,并分别使用PyObject_GenericGetDict和将其设置为新字典PyObject_GenericSetDict

>>> A.__dict__
mappingproxy(
{'__module__': '__main__',
 '__init__': <function A.__init__ at 0x1041fb598>,
 '__dict__': <attribute '__dict__' of 'A' objects>,
 '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None
})
>>> A.__dict__['__dict__'].__get__(a)
{'a': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)

当然,我们也可以从这里设置一个新字典:

>>> new_dict = {}
>>> A.__dict__['__dict__'].__set__(a, new_dict)  # a.__dict__ = new_dict
>>> a.spam = 'eggs'
>>> a.__dict__
{'spam': 'eggs'}
>>> new_dict
{'spam': 'eggs'}
>>> b = A()  # Points to `shared`
>>> b.__dict__
{'a': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,我们的类本身包含一个名为 的属性__dict__,但该__dict__属性仍然指向mappingproxy

>>> A.__dict__
mappingproxy(
{'__module__': '__main__',
 '__dict__': None,
 '__init__': <function A.__init__ at 0x1041cfae8>,
 '__weakref__': <attribute '__weakref__' of 'A' objects>,
 '__doc__': None}
)
Run Code Online (Sandbox Code Playgroud)

__dict__这样的类的属性是一种特殊的属性

>>> A.__weakref__ is A.__dict__['__weakref__']
True    
>>> A.__weakref__ = 1    
>>> A.__weakref__, A.__dict__['__weakref__']
(1, 1)

>>> A.__dict__ = {}    
AttributeError: attribute '__dict__' of 'type' objects is not writable
Run Code Online (Sandbox Code Playgroud)

我们设置的属性可以这样访问:

>>> repr(A.__dict__['__dict__'])
'None'
Run Code Online (Sandbox Code Playgroud)

在 Python 级别,我们现在无法访问实例字典,但在内部类可以使用tp_dictoffset. 正如在_PyObject_GetDictPtr.

__getattribute____setattr__使用 访问底层实例字典_PyObject_GetDictPtr

要访问正在使用的实例字典,我们实际上可以_PyObject_GetDictPtr使用 ctypes 在 Python 中实现。@user4815162342在这里做得非常雄辩。

import ctypes

def magic_get_dict(o):
    # find address of dict whose offset is stored in the type
    dict_addr = id(o) + type(o).__dictoffset__

    # retrieve the dict object itself
    dict_ptr = ctypes.cast(dict_addr, ctypes.POINTER(ctypes.py_object))
    return dict_ptr.contents.value
Run Code Online (Sandbox Code Playgroud)

继续第二种情况:

>>> magic_get_dict(a)
{'__dict__': {'a': 1, 'b': 2, 'foo': 'bar'}}  # `a` has only one attribute i.e. __dict__
>>> magic_get_dict(b)
{'__dict__': {'a': 1, 'b': 2, 'foo': 'bar'}, 'x': 100}  # `x` found
>>> magic_get_dict(b).update(shared)
>>> b.a, b.b, b.foo, b.x
(1, 2, 'bar', 100)
Run Code Online (Sandbox Code Playgroud)