12

私はこの単純なコードを持っていますが、奇妙なエラーが発生します:

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'

私は何を間違っていますか?理論的な説明をいただければ幸いです。

4

1 に答える 1

26

メタ クラスの使い方がABCMeta間違っています。ベースクラスではなく、メタクラスです。そのままお使いください。

__metaclass__Python 2 の場合、これはクラスの属性に割り当てることを意味します。

class CVIterator(object):
    __metaclass__ = ABCMeta

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

Python 3 ではmetaclass=...、クラスを定義するときに次の構文を使用します。

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

abc.ABCPython 3.4 以降、ヘルパー クラスを基本クラスとして使用できます。

from abc import ABC

class CVIterator(ABC):
    def __init__(self):
        self.n = None # the value of n is obtained in the fit method
于 2015-07-10T12:13:19.773 に答える