python中的抽象方法

时间:2015-09-07 04:49:07

标签: python python-3.x

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)

根据教程,我期待从上面的代码中获取,但是我得到了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

1 个答案:

答案 0 :(得分: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