简体   繁体   English

重定向python中的函数定义

[英]Redirecting function definitions in python

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__ . 其他方法(如__iter__也会出现同样的问题。 What is it about explicitly defining this method that works? 明确定义这个有效的方法是什么意思?

When you use brackets [] python looks in the class. 当你使用方括号[] python看起来在类中。 You must set the method in the class. 您必须在类中设置方法。

Here's your code adapted: 这是您的代码改编:

class A(dict):  
    def __init__(self):
        self['a'] = 'success'

    def __getitem__(self, name):
        print 'getitem!'
        return dict.__getitem__(self, name)

class B(object):
    def __init__(self):
        self._a = A()
        B.__getitem__ = self._a.__getitem__

b = B()
c = b['a']

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. 我无法找到关于此的参考,但基本上是因为它们是类方法,不允许是实例方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM