在追捕一個不起眼的錯誤,我無意中發現了一些通過這個小例子,最好的證明:繼承numpy.vectorize-ED功能
import numpy as np
class First(object):
def __init__(self):
self.vF = np.vectorize(self.F)
print "First: vF = ", self.vF
def F(self, x):
return x**2
class Second(First):
def __init__(self):
super(Second, self).__init__()
print "Second: vF = ", self.vF
def F(self, x):
raise RuntimeError("Never be here.")
def vF(self, x):
return np.asarray(x)*2
我想到的是Second
的實例將有明確定義vF
方法,但似乎沒有這樣的情況:
arg = (1, 2, 3)
f = First()
print "calling first.vF: ", f.vF(arg)
s = Second()
print "calling second.vF: ", s.vF(arg)
產生
First: vF = <numpy.lib.function_base.vectorize object at 0x23f9310>
calling first.vF: [1 4 9]
First: vF = <numpy.lib.function_base.vectorize object at 0x23f93d0>
Second: vF = <numpy.lib.function_base.vectorize object at 0x23f93d0>
calling second.vF:
Traceback (most recent call last):
...
RuntimeError: Never be here.
,這樣看來,s.vF
和f.vF
是同一個對象,即使s.vF == f.vF
是False
。
這是預期/已知/記錄的行爲,並numpy.vectorize
不繼承發揮很好,還是我失去了一些東西簡單嗎? (當然,在這種特殊情況下的問題很容易通過更改First.vF
正常Python的方法,或者只是沒有要求在Second
的構造super
修復。)
啊,MRO就是這個詞。啓發,謝謝! – 2013-02-13 20:30:56