2011-02-28 112 views
4

我在CPython的2.6(原來的Python實現)試圖此代碼段random.Random(蟒蛇/ CPython的2.6):問題繼承

from random import Random, random 

class Uniform(Random, object): 
    def __init__(self, min, max): 
     self._min =min 
     self._max =max 
    def randint(self): 
     return super(Uniform, self).randint (self._min, self._max) 
    def uniform(self): 
     return super(Uniform, self).uniform(self._min, self._max) 

if __name__ == '__main__': 
    a=Uniform(0., 1.2) 
    print a.uniform() 
    print a.randint() 

雖然這似乎是正確 Python的繼承,它拋出這個錯誤:

/tmp/source.py in <module>() 
    11 
    12 if __name__ == '__main__': 
---> 13 a=Uniform(0., 1.2) 
    14 print a.uniform() 
    15 print a.randint() 

TypeError: seed expected at most 1 arguments, got 2 
WARNING: Failure executing file: </tmp/source.py> 

但如果你定義

def __init__(self, min, max): 

def __init__(self, (min, max)): 

事情會奇蹟般地去「正確」 ..但最初產生的隨機數將永遠爲統一的所有實例相同的(因爲相同的初始種子的!)。

問題的根源

random.Random類是新式類,肯定它不是基本類(見/usr/lib/python2.6/random.py在Unix及其等價物在Win)。因此,我們的課程將涉及內置類的子類化。 random.Random類 - 儘管其新類型的子類在C(在/usr/lib/python2.6/random.py中看到的第一類,請參閱import _random - 它是內置類!)。

這是什麼意思?我們需要重寫__new__方法,就好像它是內置類本身(更多在這裏:problem subclassing builtin type)。

FINAL替代方法SHORT

只需添加__new__方法(即random()被進口在該「問題」的2號線和剛對象現場random.Random.seed(x)初始化對象的種子(背後傳遞的首要在/usr/lib/python2.6/random.py))。

class Uniform(Random, object): 
    def __new__(cls, *args, **kwargs): 
     return super (Uniform, cls).__new__ (cls, random()) 
    def __init__(self, min, max): 
     self._min =min 
     self._max =max 

在Python中享受內置的Mersenne Twister隨機數生成器;-)祝您好運!

回答

0

你需要在你的構造函數的開始調用Random.__init__(self, seed)(該seed參數是可選):

def __init__(self, min, max): 
    Random.__init__(self) # Use the default seed. 
    self._min =min 
    self._max =max 

另外,我不太明白爲什麼要明確擴大object爲好;擴展Random應該就夠了。