Python with overrish&super


📗 override
class TheMatrix:
    def __init__(self):
        self.person = 'person'
        self.smith = 'smith'
        self.neo = 'neo'
        self.line = 'Call trans opt: received. 2-19-98 13:24:18 REC:log'

class TheMatrixReloaded(TheMatrix):
    def _smith(self):
        self.person = 'smith'
        print(f'line: {self.smith} infects a man')
        print(f'line: The man becomes another {self.person}')
        self.line = 'Good bye, Mr. Anderson.'
        print(f'{self.smith}: ', self.line)

class TheMatrixRevolution(TheMatrix):
    def _neo(self):
        self.line = 'My name is Neo.'
        print(f'{self.neo}: ', self.line)

connection0 = TheMatrixReloaded()
connection1 = TheMatrixRevolution()

connection0._smith()
connection1._neo()
PS c:\Users> c:/Users/python.py
line: smith infects a man
line: The man becomes another smith
smith: Good bye, Mr. Anderson.
neo: My name is Neo.
継承は言うとおりです.
財産相続時に相続した財産を使うことができるように.
クラスで使用される概念を継承します.
より詳細には、親と命名されたクラスを子に継承します.
これは内部のselfオブジェクトや関数を使用する場合の概念です.
この継承方法にはoverrideとsuperがある.
overrideは、子クラスで親クラスで定義された関数またはオブジェクトに対してオーバーライド機能を実行します.
上のTheMatrixReloadクラスは現在TheMatrixクラスを継承しています.
TheMatrixのinitで定義されているperson、lineについて
TheMatrixReloadのsmithが上書きされています.
📗 super
class TheMatrix:
    def __init__(self):
        self.person = 'person'
        self.smith = 'smith'
        self.neo = 'neo'
        self.line = 'Call trans opt: received. 2-19-98 13:24:18 REC:log'

class TheMatrixReloaded(TheMatrix):
    def _smith(self):
        self.person = 'smith'
        print(f'line: {self.smith} infects a man')
        print(f'line: The man becomes another {self.person}')
        self.line = 'Good bye, Mr. Anderson.'
        print(f'{self.smith}: ', self.line)

class TheMatrixRevolution(TheMatrix):
    def _neo(self):
        self.line = 'My name is Neo.'
        print(f'{self.neo}: ', self.line)

class TheMatrixFour2021(TheMatrixRevolution):
    def _neo(self):
        super()._neo()

connection3 = TheMatrixFour2021()
connection3._neo()
PS c:\Users> c:/Users/python.py
neo: My name is Neo.
親クラスで定義された関数の場合、子クラスもsuperを使用したい場合はsuperを使用します.
特に、特定のオブジェクトを上書きした後も他のオブジェクトを使用し続ける場合は、superメソッドが一般的に使用されます.
上記のコードから、TheMatrixFour 2021は、TheMatrixRevolutionを継承する場合である.
TheMatrixFour 2021クラスがneo関数の下で既存のオブジェクトに対する変更または新しいオブジェクトを宣言した場合、それは上書きされます.
TheMatrixRevolutionクラスのneo関数をsuperで直接インポートして使用します.
この使い方はdjangoでよく使われます.
特に、インポートしたライブラリは書き換えられることが多く、superのように適切に使用すると、一部のオブジェクトの論理のみが変更され、他のオブジェクトが使用可能になり、機能の実現が容易になる可能性があります.