【问题标题】:Abstract method in pythonpython中的抽象方法
【发布时间】:2015-09-07 12:54:04
【问题描述】:
import abc

class SetterGetter(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def set_val(self, inp):
        return

    @abc.abstractmethod
    def get_val(self):
        return

class TryAbsMethod(SetterGetter):
    def get_val(self):
        return self.inp

    def set_valz(self, inp):
        self.inp = inp

a = TryAbsMethod()
print(a)

根据教程,我期望从上面的代码中得到 excption,但我得到了来自 python 的输出,这很奇怪,有人可以解释一下为什么吗?

输出得到

/usr/bin/python3.4 /home/murtuza/MyCodes/abstract.py
<__main__.TryAbsMethod object at 0x7f93ba8ab048>

Process finished with exit code 0

预期的异常

TypeError: Can't instantiate abstract class TryAbsMethod with abstract method set_val

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您使用的是 Python 3.x。在 Python 3.x 中,元类声明语法发生了变化。

class SetterGetter(object, metaclass=abc.ABCMeta):  # <---
    @abc.abstractmethod
    def set_val(self, inp):
        return

    @abc.abstractmethod
    def get_val(self):
        return

Customizing class creation - Data model - Python 3.x documentationPEP3115 - Metaclasses in Python 3

【讨论】:

猜你喜欢
  • 2011-08-16
  • 2011-05-21
  • 2014-07-09
  • 1970-01-01
  • 2022-11-22
  • 2022-06-25
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多