- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用以下代码:
class X( object ):
def __init__( self ):
self.value = 0
def __iadd__( self, value ):
self.value += value
return self
class Y( object ):
def __init__( self ):
self.fields = { 'test': X() }
def __getitem__( self, key ):
return( self.fields[ key ] )
def __getattr__( self, key ):
return self.fields[ key ]
obj = Y()
obj.test += 1
print( obj.test.value )
obj['test'] += 1
print( obj.test.value )
将 __iadd__
与 __getattr__
一起使用会起作用,但是在使用 __getitem__
时会出现错误:
TypeError: 'Y' object does not support item assignment
发生。
我知道 __iadd__
实际上是 x = x.__iadd__(y)
,但是我不知道为什么它不能与 __getitem__ 一起使用
。
谢谢。
最佳答案
obj.test += 1
工作的原因是 obj.__setattr__
有一个允许它工作的默认实现(虽然可能不是你想要的方式工作)——即,它在实例字典中存储对返回的 X
对象的引用。您可以通过以下方式观看它的发生:
>>> obj = Y()
>>> obj.test
<__main__.X object at 0x0000024BF247B220>
>>> obj.__dict__
{'fields': {'test': <__main__.X object at 0x0000024BF247B220>}}
>>> obj.test += 1
>>> obj.__dict__
{'fields': {'test': <__main__.X object at 0x0000024BF247B220>}, 'test': <__main__.X object at 0x0000024BF247B220>}
请注意,现在有一个 test
属性 在您的 fields
字典之外!两个字典都指向的仍然只有一个 X
对象(因为你的 __iadd__
返回了 self
,没有新的 X
曾经被创造过)。
当你执行 obj.test += 1
时,发生的事情是:
obj.__setattr__("test", obj.__getattr__("test").__iadd__(1))
__setattr__
调用在 obj.__dict__
中创建新的“测试”条目。
相反,当您执行 obj["test"] += 1
时,这将转化为:
obj.__setitem__("test", obj.__getitem__("test").__iadd__(1))
__setitem__
引发了异常——与 __setattr__
不同,没有默认的 object.__setitem__
允许 obj[ "test"] = obj["test"] + 1
开始工作。
关于python - 为什么 "__iadd__"在与 "__getitem__"和 "__getattr__"一起使用时表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71858949/
__getattr__ 可用于定义对象的属性。例如。以下代码将返回'bar'。 class Test(object): def __getattr__(self, key):
我一直在尝试实现 __getattr__ 函数,如下例所示: PEP 562 -- Module __getattr__ and __dir__ 我不明白为什么这段简单的代码: # lib.py de
读一本书,我遇到了这段代码...... # module person.py class Person: def __init__(self, name, job=None, pay=0):
我遇到了内置的 __getattr__ 并且想知道什么时候可以使用它。我很难从文档中想到实际用途 http://docs.python.org/reference/datamodel.html# .什
我正在尝试找到一种方法来设置封装到 class 中的 dict 值,例如使用 __getattr__ 我可以返回内部 dict 值,但是即使属性存在,也会调用 __setattr__,这让我的实现变得
我想在类实例化期间更改 __getattr__。例如: class AttrTest(object): def __init__(self): self.__getattr__
这个问题在这里已经有了答案: How can I intercept calls to python's "magic" methods in new style classes? (4 个答案)
我必须自定义 __getattr__ 来调用另一个函数来读取。 除了 help(object.attr) 不起作用外,这很好用。此代码用于交互式环境,因此 help() 对我们来说变得很重要。 是否有
当未找到属性时,将调用 object.__getattr__。是否有等效的方法来拦截未定义的方法? 最佳答案 没有区别。方法也是一种属性。 (但是,如果您希望该方法有一个隐式的“self”参数,您将不
我的类(class)有一个字典,例如: class MyClass(object): def __init__(self): self.data = {'a': 'v1', '
如何在类、模块上实现 __getattr__ 的等价物? 示例 当调用一个模块的静态定义属性中不存在的函数时,我希望在该模块中创建一个类的实例,并在其上调用与在模块上的属性查找中失败的名称相同的方法.
如何覆盖 __getattr__一个类的方法而不破坏默认行为? 最佳答案 覆盖 __getattr__ 应该没问题 - __getattr__ 仅作为最后的手段调用,即如果实例中没有与名称匹配的属性。
感谢您花时间阅读本文。希望你在这些陌生的时刻一切都好。 我正在实现一个类并开始研究如何为其属性提供自动完成功能。从我的在线研究中,我得出的结论是 ipython 补全来自 __dir__ 方法。 __
对于 Thing 类,当我调用一个未定义的方法时,例如 .doamethod()... class Thing: def __init__(self): pass de
我有一个类,它是成员的容器。所有成员都属于同一类型。 class A(int): def __init__(self, n): super().__init__()
import random class Foo(object): def __init__(self): self._name = ''.join([chr(65 + rand
在《学习Python 3rd》中,我看到了这段代码 class wrapper: def __init__(self, object): self.wrapped = obje
在我的基于 Flask sqlalchemy 的应用程序中,我有一个这样的模型: class Foo(object): start_date = db.Column(db.DateTime()
正如标题所说。似乎无论我做什么,都不会调用 __getattr__。例如,我也尝试过(我知道这很荒谬),但不出所料没有回应。就好像 __getattr__ 在元类中被禁止了一样。 如果有任何关于此文档
这个问题在这里已经有了答案: Overriding special methods on an instance (5 个答案) 关闭 5 年前。 我现在正在从事一个项目,该项目处理抽象数学意义上的
我是一名优秀的程序员,十分优秀!