How to implement virtual methods in Python?

前端 未结 6 1021
自闭症患者
自闭症患者 2020-12-04 11:41

I know virtual methods from PHP or Java.

How can they be implemented in Python?

Or have I to define an empty method in an abstract class and override it?

6条回答
  •  旧时难觅i
    2020-12-04 12:38

    Actually, in version 2.6 python provides something called abstract base classes and you can explicitly set virtual methods like this:

    from abc import ABCMeta
    from abc import abstractmethod
    ...
    class C:
        __metaclass__ = ABCMeta
        @abstractmethod
        def my_abstract_method(self, ...):
    

    It works very well, provided the class does not inherit from classes that already use metaclasses.

    source: http://docs.python.org/2/library/abc.html

提交回复
热议问题