Skip to main content

Python 抽象方法 (Abstract Method)

參考:

Python 函數
Instance Object 追加 Method: abstract method 不可以以追加的方式實作

Abstract Method

  • 需使用 abc 套件
    • ABCMeta Class
    • @abstractmethod annotation
  • 子類別若未實作 Abstract Method 回拋出:
    • TypeError: Can't instantiate abstract class ClassName with abstract method MethodName
  • metaclass : Python interpreter 用來管理建構 type 時使用

from abc import ABCMeta
from abc import abstractmethod

# 注意: metaclass
class Html_Form(metaclass=ABCMeta):
def __init__(self):
pass

@abstractmethod
def submit(self, forward_to, **kwargs):
print('Submit Abstract Html_Form')


class LoginForm(Html_Form):

def submit(self, forward_to, **kwargs):
print('Submit LoginForm')
print(kwargs)


f = LoginForm()
f.submit(forward_to='roadmap', username='username', pwd='password')