简体   繁体   English

Python:执行抽象方法

[英]Python: enforcing abstract method

I have written the follow code to demonstrate abstract methods that must be implemented by its subclasses. 我编写了以下代码来演示必须由其子类实现的抽象方法。 I read that when a method in a parent class is decorated as abstract, its subclass must implement it otherwise it cannot be instantiated. 我读到,当父类中的方法装饰为抽象时,其子类必须实现它,否则无法实例化。 However, in the following code, the 'Slug' subclass does not implement the abstract method, yet it can still instantiate without errors being thrown. 但是,在以下代码中,“ Slug”子类未实现abstract方法,但仍可以实例化而不会引发错误。 I thought in this case Python will complain? 我以为在这种情况下,Python会抱怨吗?

Have I misunderstood something? 我误会了吗?

Thanks 谢谢

import abc

class Animal(object):

    __metaclass__ = abc.ABCMeta

    def __init__(self, species):
        self._species=species

    def get_species(self):
        return self._species

    @abc.abstractmethod
    def eat(self):
        pass

class Slug(Animal):

    def __init(self, species):
        super(species)

    def run(self):
        print("running")

    # def eat(self):
    #     pass


sl = Slug("slug")
print(sl.get_species())

no, you understood perfectly well! 不,您完全理解! it is just that the python 3 syntax for abc.ABCMeta is: 仅仅是abc.ABCMeta的python 3语法是:

class Animal(metaclass=abc.ABCMeta):
    ...

instead of __metaclass__ = abc.ABCMeta which was used in python 2. alternatively you can just inherit from ABC : class Animal(abc.ABC): . 而不是python 2中使用的__metaclass__ = abc.ABCMeta 。或者,您也可以仅继承自ABCclass Animal(abc.ABC): see doc . 文档

and then: 接着:

class Slug(Animal):

    def __init(self, species):
        super.__init__(species)

    ...

this will result in 这将导致

Traceback (most recent call last):
  File "/home/.../...py", line 33, in <module>
    sl = Slug("slug")
TypeError: Can't instantiate abstract class Slug with abstract methods eat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM