「Python3.9」親クラスのコンストラクタを実行するサンプル

環境
Python 3.9.13
Windows 11 Pro 21H2 64bit
PyCharm 2022.2.1 (Community Edition)

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class 親クラス名:
def __init__(self, 引数):
class 子クラス名(親クラス名):
   def __init__(self, 引数):
super().__init__(引数)
class 親クラス名: def __init__(self, 引数): class 子クラス名(親クラス名):    def __init__(self, 引数): super().__init__(引数)
class 親クラス名:
   def __init__(self, 引数):

class 子クラス名(親クラス名):
   def __init__(self, 引数):
        super().__init__(引数)

superを使って、親クラスのコンストラクタを使用します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
#親クラスの定義
class People:
def __init__(self, name):
self.userName = name
#子クラスの定義
class Student(People):
def __init__(self, name):
# superを利用
super().__init__(name)
ss = Student("テスト 太郎")
print(ss.userName)
# coding: utf-8 #親クラスの定義 class People: def __init__(self, name): self.userName = name #子クラスの定義 class Student(People): def __init__(self, name): # superを利用 super().__init__(name) ss = Student("テスト 太郎") print(ss.userName)
# coding: utf-8

#親クラスの定義
class People:
    def __init__(self, name):
        self.userName = name
#子クラスの定義
class Student(People):
    def __init__(self, name):
        # superを利用
        super().__init__(name)

ss = Student("テスト 太郎")
print(ss.userName)

実行結果
テスト 太郎

Python

Posted by arkgame