0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

プロパティー・アクセス制限

Last updated at Posted at 2020-02-03
class Car(object):
    def __init__(self, model=None):
        self.model = model
    
    def run(self):
        print('run')

class TeslaCar(Car):
    def __init__(self, model='Model A',
                 enable_auto_run=False,
                 password='123'):
        super().__init__(model)
        self._enable_auto_run = enable_auto_run
        self.password = password
    
    @property
    def enable_auto_run(self):
        return self._enable_auto_run
    
    @enable_auto_run.setter
    def enable_auto_run(self, is_able):
        if self.password == '456':
            self._enable_auto_run = is_able
        else:
            raise ValueError
    
    def run(self):
        print('run very fast')
    
    def auto_run(self):
        print('auto run')

tesla_car = TeslaCar(password='456')
tesla_car.enable_auto_run = True
print(tesla_car.enable_auto_run)
実行結果
True
@property
def enable_auto_run(self):
    return self._enable_auto_run


_enable_auto_runを外部から操作できない様にする。
が、

@enable_auto_run.setter
def enable_auto_run(self, is_able):
    if self.password == '456':
        self._enable_auto_run = is_able
    else:
        raise ValueError


passwordが'456'の場合、
enable_auto_runを外部から操作でき、
それ以外の場合は、
ValueErrorを起こす。

なので、最後の三行を

tesla_car = TeslaCar(password='123')
tesla_car.enable_auto_run = True
print(tesla_car.enable_auto_run)

にして、
passwordを'123'にすると、
ValueErrorが発生する。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?