26
18

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 5 years have passed since last update.

Python ゲッター、セッターなどサンプル

Posted at

方法1

# -*- coding:utf-8 -*-

class Test(object):
    def __init__(self):
        self._x = None

    def getx(self):
        print "getx."
        return self._x

    def setx(self, value):
        print "setx."
        self._x = value

    def delx(self):
        print "delx."
        del self._x

    x = property(getx, setx, delx)

if __name__ == "__main__":
    test = Test()

    test.x = 1
    test.x
    del test.x

実行結果

setx.
getx.
delx.

方法2

# -*- coding:utf-8 -*-

class Test(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        print "property x."
        return self._x

    @x.setter
    def x(self, value):
        print "setter x."
        self._x = value

    @x.deleter
    def x(self):
        print "deleter x."
        del self._x

if __name__ == "__main__":
    test = Test()

    test.x = 1
    test.x
    del test.x

実行結果

setter x.
property x.
deleter x.
26
18
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
26
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?