0
0

More than 3 years have passed since last update.

Pythonのpropertyについてまとめ

Last updated at Posted at 2020-08-09

概要

  • pythonのpropertyについて理解が怪しかったので例を交えて整理しておく目的で記事を書きました

例題

  • 下記コードを例に説明していく

class Dog(object):
    def __init__(self):
        self.name = 'John'

dog = Dog()
print(dog.name)

何も設定しない場合

  • 例題に記載してある通りのコードを実行する
  • outputは"John"となる

class変数を下記に変更


class Dog(object):
    def __init__(self):
        self.__name = 'John'

dog = Dog()
print(dog.name)

上記のoutputは下記となる

Traceback (most recent call last):
〜(省略)〜
    print(dog.name)
AttributeError: 'Dog' object has no attribute 'name'
  • self.name = 'John'self.__name = 'John'とする事で外部からclass変数が呼び出せなくなる

getterを使用してclass変数を外部から参照させる


class Dog(object):
    def __init__(self):
        self.__name = 'John'
    @property ##getterの設定
    def name(self):
          return self.__ name

dog = Dog()
print(dog.name)
  • 上記のoutputはJohnとなる
  • getterを使用する事によって外部からclass変数=nameが参照できるようになる

setterを使用してclass変数を外部から変更できるようにする


class Dog(object):
    def __init__(self):
        self.__name = 'John'

    @name.setter ##setterの設定
    def name(self, dogname):
        self.__name = dogname

dog.name = 'sandy'
print(dog.name)
  • 上記のoutputはsandyとなる
  • setterを使用する事によって外部からclass変数=nameの内容を変更できるようになる

参照

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