2015-07-10 61 views
3

我有這個簡單的代碼,我得到一個奇怪的錯誤:蟒蛇錯誤時從派生的類和抽象一個

from abc import ABCMeta, abstractmethod 

class CVIterator(ABCMeta): 

    def __init__(self): 

     self.n = None # the value of n is obtained in the fit method 
     return 


class KFold_new_version(CVIterator): # new version of KFold 

    def __init__(self, k): 
     assert k > 0, ValueError('cannot have k below 1') 
     self.k = k 
     return 


cv = KFold_new_version(10) 

In [4]: --------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-4-ec56652b1fdc> in <module>() 
----> 1 __pyfile = open('''/tmp/py13196IBS''');exec(compile(__pyfile.read(), '''/home/donbeo/Desktop/prova.py''', 'exec'));__pyfile.close() 

/home/donbeo/Desktop/prova.py in <module>() 
    19 
    20 
---> 21 cv = KFold_new_version(10) 

TypeError: __new__() missing 2 required positional arguments: 'bases' and 'namespace' 

我在做什麼錯?理論解釋將不勝感激。

回答

9

錯誤地使用了ABCMeta元類。它是一個類,不是基類。像這樣使用它。

對於Python 2,這意味着它分配給了__metaclass__屬性的類:

class CVIterator(metaclass=ABCMeta): 
    def __init__(self): 
     self.n = None # the value of n is obtained in the fit method 

class CVIterator(object): 
    __metaclass__ = ABCMeta 

    def __init__(self): 
     self.n = None # the value of n is obtained in the fit method 

在Python 3,你定義的類時所使用的metaclass=...語法從Python 3.4開始,可以使用abc.ABC helper class作爲基類:

from abc import ABC 

class CVIterator(ABC): 
    def __init__(self): 
     self.n = None # the value of n is obtained in the fit method