Python abstract classes - how to discourage instantiation?

后端 未结 5 1456
面向向阳花
面向向阳花 2021-02-07 04:58

I come from a C# background where the language has some built in \"protect the developer\" features. I understand that Python takes the \"we\'re all adults here\" approach and

5条回答
  •  鱼传尺愫
    2021-02-07 05:41

    If you're using Python 2.6 or higher, you can use the Abstract Base Class module from the standard library if you want to enforce abstractness. Here's an example:

    from abc import ABCMeta, abstractmethod
    
    class SomeAbstractClass(object):
        __metaclass__ = ABCMeta
    
        @abstractmethod
        def this_method_must_be_overridden(self):
            return "But it can have an implementation (callable via super)."
    
    class ConcreteSubclass(SomeAbstractClass):
        def this_method_must_be_overridden(self):
            s = super(ConcreteSubclass, self).this_method_must_be_overridden()
            return s.replace("can", "does").replace(" (callable via super)", "")
    

    Output:

    >>> a = SomeAbstractClass()
    Traceback (most recent call last):
      File "", line 1, in 
        a = SomeAbstractClass()
    TypeError: Can't instantiate abstract class SomeAbstractClass with abstract
    methods this_method_must_be_overridden
    >>> c = ConcreteSubclass()
    >>> c.this_method_must_be_overridden()
    'But it does have an implementation.'
    

提交回复
热议问题