初始化从派生的类和抽象类时出现python错误
我有一个简单的代码,我得到一个奇怪的错误:初始化从派生的类和抽象类时出现python错误,python,inheritance,abstract-base-class,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 versi
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'
从abc导入ABCMeta,abstractmethod
类CVIterator(ABCMeta):
定义初始化(自):
self.n=None#n的值通过拟合方法获得
返回
类KFold_new_version(CV迭代器):#KFold的新版本
定义初始化(self,k):
断言k>0,ValueError('k不能低于1')
self.k=k
返回
cv=KFold\u new\u版本(10)
在[4]中:---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1 _pyfile=open(''/tmp/py13196IBS');exec(compile(uu pyfile.read(),'''/home/donbeo/Desktop/prova.py'','exec')__pyfile.close()
/home/donbeo/Desktop/prova.py in()
19
20
--->21 cv=KFold\u new\u版本(10)
TypeError:\uuuuu new\uuuuuu()缺少2个必需的位置参数:“base”和“namespace”
我做错了什么?请提供理论解释 您错误地使用了
ABCMeta
元类。它是一个元类,而不是基类。这样使用它
对于Python2,这意味着将其分配给类上的\uuuuuuuuuuuuuuuuuuuuuuuuuuu元类
属性:
class CVIterator(object):
__metaclass__ = ABCMeta
def __init__(self):
self.n = None # the value of n is obtained in the fit method
class CVIterator(metaclass=ABCMeta):
def __init__(self):
self.n = None # the value of n is obtained in the fit method
在Python3中,定义类时使用元类=…
语法:
class CVIterator(object):
__metaclass__ = ABCMeta
def __init__(self):
self.n = None # the value of n is obtained in the fit method
class CVIterator(metaclass=ABCMeta):
def __init__(self):
self.n = None # the value of n is obtained in the fit method
从Python 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