LoginSignup
0
0

More than 3 years have passed since last update.

setterとgetter

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

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


class ToyotaCar(Car):
    def __init__(self, model,enable_auto_run = False):
        #self.model = modelとも書けるが、superを使って親メソッドを読み出せる
        super().__init__(model)
        #getterやsetterを使って変数にアクセスさせたい場合は、変数名の前に_をつける
        self._enable_auto_run = enable_auto_run
        #外から完全に遮蔽するには変数名の前に_を2つ付ける
        #self.__enable_auto_run = enable_auto_run

    @property
    def enable_auto_run(self):
        return self._enable_auto_run

    @enable_auto_run.setter
    def enable_auto_run(self,is_enable):
        self._enable_auto_run = is_enable

    #メソッドのオーバーライド
    def run(self):
        print('fast fun')


car = Car()
car.run()

toyotar_car = ToyotaCar('Lexus')
toyotar_car.enable_auto_run = True
print(toyotar_car.enable_auto_run)

run
True
0
0
1

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
0