type和__class__之间的区别

时间:2015-12-02 12:21:18

标签: python django types

Django源代码:

def new_method_proxy(func):
    def inner(self, *args):
        if self._wrapped is empty:
            self._setup()
        return func(self._wrapped, *args)
    return inner

class LazyObject(object):

    _wrapped = None

    def __init__(self):
        self._wrapped = empty

    __getattr__ = new_method_proxy(getattr)

    def _setup(self):
        # Must be implemented by subclasses to initialize the wrapped object.
        raise NotImplementedError('subclasses of LazyObject must provide a _setup() method')

    def __deepcopy__(self, memo):
        if self._wrapped is empty:
            # We have to use type(self), not self.__class__, because the
            # latter is proxied.
            result = type(self)()
            memo[id(self)] = result
            return result
        return copy.deepcopy(self._wrapped, memo)

__deepcopy__()函数中,注释:

We have to use type(self), not self.__class__, because the latter is proxied.

这是什么意思? type()__class__之间有什么区别?

1 个答案:

答案 0 :(得分:1)

source code中的更远一点:

# Need to pretend to be the wrapped class, for the sake of objects that
# care about this (especially in equality tests)
__class__ = property(new_method_proxy(operator.attrgetter("__class__")))

在这里,您会看到__class__属性(最终只是一个普通属性)被自定义定义覆盖。这个新定义是一个返回代理类值的属性。

type(obj)绕过新的__class__属性,并返回LazyObject类,而不是代理类。