gpt4 book ai didi

python - 类型和 __class__ 之间的区别

转载 作者:太空宇宙 更新时间:2023-11-04 05:40:38 24 4
gpt4 key购买 nike

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

关于python - 类型和 __class__ 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com