nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

クラスのメソッドのオーバーライドとsuperによる親メソッドの呼び出し [Python]

クラスのメソッドのオーバーライドとsuperによる親メソッドの呼び出し

<コード>

class Car(object):
    def __init__(self, model=None):
        self.model = model

    def run(self):
        print('run')


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


class TeslaCar(Car):
    def __init__(self, model="Model S", enable_run=False):
        # 親のinit関数を呼び出す
        super().__init__(model)
        self.enable_auto_run = enable_run

    def run(self):
        print('super 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('########')

tesula_car = TeslaCar('Model_S', True)
print(tesula_car.model)
print(tesula_car.enable_auto_run)
tesula_car.run()
tesula_car.auto_run()

<出力結果>

run
########
Lexus
fast
########
Model_S
True
super fast
auto_run