在上初始化派生自和抽象的类时发生python错误

2024-09-30 12:11:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'

我做错什么了?如果有理论上的解释,我们将不胜感激。在


Tags: oftheinselfnewreturninitversion
1条回答
网友
1楼 · 发布于 2024-09-30 12:11:54

您错误地使用了ABCMeta元类。它是一个meta类,而不是基类。就这样用吧。在

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

class CVIterator(object):
    __metaclass__ = ABCMeta

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

在Python3中,定义类时使用metaclass=...语法:

^{pr2}$

从Python3.4开始,可以使用^{} 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

相关问题 更多 >

    热门问题