Skip to main content
 首页 » 编程设计

python之类型和 __class__ 之间的区别

2025年05月04日19softidea

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__ 有什么区别?

请您参考如下方法:

在 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 类,而不是代理类。