【问题标题】:python error when initializing a class derived from and abstract one初始化派生自和抽象类的类时出现python错误
【发布时间】:2015-07-10 12:05:11
【问题描述】:

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

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'

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

【问题讨论】:

    标签: python inheritance abstract-base-class


    【解决方案1】:

    您错误地使用了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
    

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

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

    从 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2012-04-22
      • 2018-03-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      相关资源
      最近更新 更多