初始化派生自和抽象的类时出现python错误

Don*_*beo 6 python inheritance abstract-base-class

我有这个简单的代码,我得到一个奇怪的错误:

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'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?理论上的解释将不胜感激.

Mar*_*ers 14

您ABCMeta错误地使用了元类.它是一个元类,而不是基类.这样使用它.

对于Python 2,这意味着将它分配给__metaclass__类的属性:

class CVIterator(object):
    __metaclass__ = ABCMeta

    def __init__(self):
        self.n = None # the value of n is obtained in the fit method
Run Code Online (Sandbox Code Playgroud)

在Python 3中,您metaclass=...在定义类时使用语法:

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

从Python 3.4开始,您可以使用abc.ABC辅助类作为基类:

from abc import ABC

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