0
1

More than 3 years have passed since last update.

クラスの継承とsuper関数

Posted at
class Car(object):
    def __init__(self, model=None):
        self.model = model
    def run(self):
        print('run')

class ToyotaCar(Car):
    def run(self):
        print('run fast')

class TeslaCar(Car):
    def __init__(self, model='Model A', enable_auto_run=False):
        super().__init__(model)
        self.enable_auto_run = enable_auto_run
    def run(self):
        print('run very fast')
    def auto_run(self):
        print('auto run')

car = Car()
car.run()

print('############')

toyota_car = ToyotaCar('Lexus')
print(toyota_car.model)
toyota_car.run()

print('############')

tesla_car = TeslaCar('Model S')
print(tesla_car.model)
tesla_car.run()
tesla_car.auto_run()
実行結果
run
############
Lexus
run fast
############
Model S
run very fast
auto run

TeslaCarクラスのコンストラクターは、
本来、

def __init__(self, model='S Model', enable_auto_run=False):
        self.model = model
        self.enable_auto_run = enable_auto_run

と書くところであるが、
スーパークラスのコンストラクターと同じ処理をするので、
super関数を使って書く事ができる。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1