【E資格対策】Python クラス講座
クラス講座
クラスとインスタンス
class Person: pass # 何もしない # インスタンス作成 Alice = Person() # インスタンス変数 Alice.name = "Alice" Alice.age = 18 # インスタンスメソッド class Person2: def introduce(self): # selfは、お決まりの形 print(self.name) print(self.age) Bob = person2() Bob.name = "Bob" Bob.age = 29 Bob.introduce() # 特殊なメソッド class Person3: def __init__(self): # インスタンス作成時に呼ばれる。初期化で使う。 def __call__(self): # メソッド名の記載が不要で呼べるメソッド。 # 例) # Calor = Person3 # Calor() # __call__内の処理が呼ばれる
他のpythonファイルのクラス読み込み
from sample import SampleClass # from ファイル名(sample.py) import クラス名
継承・オーバーライド
# 親クラス class Person: def __init__(self, name, age): self.name = name self.age = age # 子クラス class Student(Person): def __init__(self, name, age, school): super().__init__(name, age) # オーバーライド self.school = school def introduce(self): print(f"{self.name}は、{self.age}歳で、{self.school}です")