Python3抽象类TypeError未引发

时间:2016-05-21 13:47:33

标签: python-2.7 python-3.x exception abstract-class

我正在运行python 2.7,3.4和3.5。只有2.7使用以下代码引发TypeError。我想知道我做错了什么,这是一个知道错误还是别的什么?

from abc import ABCMeta, abstractmethod

class Base(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def bar(self):
        pass


class Concrete(Base):
    pass


confused = Concrete()

在Python 2.7中,我得到以下(有用)错误:

Traceback (most recent call last):
  File "confused.py", line 16, in <module>
    confused = Concrete()
TypeError: Can't instantiate abstract class Concrete with abstract methods bar

但是在Python3.x中它运行没有错误(坏)。感谢。

2 个答案:

答案 0 :(得分:0)

python3中的抽象基类更改为:

import abc

class Base(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def bar(self):
        pass


class Concrete(Base):
    pass


Concrete() # Will raise a TypeError

答案 1 :(得分:0)

它们在Python2.x和Python3.x中的行为方式不同。

Python3.6

# importing abstract base classes module
import abc

class GetterSetter(abc.ABC):
    '''
    ABSTRACT BASE CLASSES:

    -  An abstract base class is a kind of 'model' for other classes to be defined.
        - It is not designed to construct instances, but can be subclassed by regular classes

    - Abstract classes can define interface, or methods that must be implemented by its subclasses.

    '''


    # Abstract classes are not designed to be instantiated, only to be subclassed

    #  decorator for abstract class
    @abc.abstractmethod
    def set_val(self, input):
        """set the value in the instance"""
        return

    @abc.abstractmethod
    def get_val(self):
        """Get and return a value from the instance..."""
        return

# Inheriting from the above abstract class
class MyClass(GetterSetter):

    # methods overriding in the GetterSetter
    def set_val(self, input):
        self.val = input

    def get_val(self):
        return self.val


# Instantiate
x = MyClass()
print(x) # prints the instance <__main__.MyClass object at 0x10218ee48>
x = GetterSetter() #throws error, abstract classes can't be instantiated

Python2.x

import abc

class GetterSetter(object):
    # meta class is used to define other classes
    __metaclass__ = abc.ABCMeta


    #  decorator for abstract class
    @abc.abstractmethod
    def set_val(self, input):
        """set the value in the instance"""
        return

    @abc.abstractmethod
    def get_val(self):
        """Get and return a value from the instance..."""
        return

# Inheriting from the above abstract class
class MyClass(GetterSetter):

    # methods overriding in the GetterSetter
    def set_val(self, input):
        self.val = input

    def get_val(self):
        return self.val


# Instantiate
x = GetterSetter()
print(x)
x = GetterSetter() #throws error, abstract classes can't be instantiated

检查我的回答here