gpt4 book ai didi

python - 在 Python 中分配(或重新重载)赋值运算符时遇到问题

转载 作者:太空狗 更新时间:2023-10-30 00:36:35 24 4
gpt4 key购买 nike

我在分配赋值运算符时遇到问题。

我已经成功重载了 __setattr__。但是在对象初始化之后,我希望 __setattr__ 做一些别的事情,所以我尝试将它分配给另一个函数,__setattr2__

代码:

class C(object):

def __init__(self):
self.x = 0
self.__setattr__ = self.__setattr2__

def __setattr__(self, name, value):
print "first, setting", name
object.__setattr__(self, name, value)

def __setattr2__(self, name, value):
print "second, setting", name
object.__setattr__(self, name, value)

c = C()
c.x = 1

我得到的:

first, setting x
first, setting __setattr__
first, setting x

我想要/期望的:

first, setting x
first, setting __setattr__
second, setting x

最佳答案

From the docs :

Special method lookup for new-style classes

For new-style classes, implicit invocations of special methods areonly guaranteed to work correctly if defined on an object’s type, notin the object’s instance dictionary. That behaviour is the reason whythe following code raises an exception (unlike the equivalent examplewith old-style classes):

>>> class C(object):
... pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()

关于python - 在 Python 中分配(或重新重载)赋值运算符时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203185/

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