python 中的重定向函数定义
这是一个非常人为的示例,因为解释我最终实现该解决方案的上下文并不容易。 然而,如果有人能回答为什么会出现这种特殊现象,我将不胜感激。
示例:
class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(self, name):
print 'getitem'
return dict.__getitem__(name)
class B(object):
def __init__(self):
self._a = A()
setattr(self, '__getitem__', self._a.__getitem__)
b = B()
c = b['a']
此输出:
c = b['a']
TypeError: 'B' object is unsubscriptable
尽管这是一种奇怪的方法(显然子类化会更合乎逻辑),但为什么它找不到我明确设置的方法?
如果我这样做:
dir(b)
我得到这个:
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_a']
其他方法(例如 __iter__
)也会出现同样的问题。 显式定义这个有效的方法有什么意义?
This is a very contrived example as it's not easy to explain the context in which I have ended up implementing this solution. However, if anyone can answer why this particular peculiarity happens, I'd be grateful.
The example:
class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(self, name):
print 'getitem'
return dict.__getitem__(name)
class B(object):
def __init__(self):
self._a = A()
setattr(self, '__getitem__', self._a.__getitem__)
b = B()
c = b['a']
This outputs:
c = b['a']
TypeError: 'B' object is unsubscriptable
Even though it's a bizarre way of doing this (clearly subclassing would be more logical), why doesn't it find the method I have explicitly set?
If I do this:
dir(b)
I get this:
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_a']
The same issue occurs with other methods such as __iter__
. What is it about explicitly defining this method that works?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当你使用方括号
[]
时,Python会在类中查找。 您必须在类中设置该方法。这是您的代码:
When you use brackets
[]
python looks in the class. You must set the method in the class.Here's your code adapted:
这是因为您无法即时重写特殊的类方法。
我无法找到关于此的参考,但基本上是因为它们是类方法并且不允许是实例方法。
This is because you can't override special class methods on the fly.
I wasn't able to find a reference about this but is basically because they are class methods and are not allowed to be instance methods.