【问题标题】:Require inheritance in Python? [duplicate]在 Python 中需要继承? [复制]
【发布时间】:2020-07-20 08:44:13
【问题描述】:

什么是要求继承的最安全方法?目前我正在做类似的事情:

>>> class A:  # Never instantiate by itself.
...     def a(self):
...         self.foo()
... 
... class B(A):
...     def foo(self):
...         print('123')
... 
... class C(A):
...     def foo(self):
...         print('456')
...         
>>> B().a()
123
C().a()
456
>>> A().a()  # Expect an error.
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 3, in a
AttributeError: 'A' object has no attribute 'foo'

这是最好的方法吗?

【问题讨论】:

    标签: python inheritance


    【解决方案1】:

    您可以使用abc 模块中的abstractmethodABC

    In [1]: from abc import ABC, abstractmethod                                                    
    
    In [2]: class A(ABC): 
       ...:     @abstractmethod 
       ...:     def foo(self): 
       ...:         ... 
       ...:                                                                        
    
    In [3]: class B(A): 
       ...:     def foo(self): 
       ...:         print("ok") 
       ...:                                                                        
    
    In [4]: class C(A): 
       ...:     def not_foo(self): 
       ...:         pass 
       ...:                                                                        
    
    In [5]: c = C()                                                                
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-19-1ef1f2c22529> in <module>
    ----> 1 c = C()
    
    TypeError: Can't instantiate abstract class C with abstract methods foo
    

    通过将基类定义为抽象类并将abstractmethod装饰器设置为方法,您可以要求方法被子类化。

    【讨论】:

      猜你喜欢
      • 2018-01-15
      • 2015-01-29
      • 2020-04-21
      • 2019-01-04
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2018-02-14
      相关资源
      最近更新 更多