Samples of Python getters, setters, etc.

Method 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

Execution result

setx.
getx.
delx.

Method 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

Execution result

setter x.
property x.
deleter x.

Recommended Posts

Samples of Python getters, setters, etc.
Basics of Python ①
Basics of python ①
Copy of python
OpenCV Samples (Python)
Introduction of Python
[Python3] Coarse graining of numpy.ndarray Speed comparison etc.
[Python] Operation of enumerate
List of python modules
Unification of Python environment
Copy of python preferences
Convenient Python methods, etc.
Basics of Python scraping basics
That of / etc / shadow
[python] behavior of argmax
Usage of Python locals ()
the zen of Python
Installation of Python 3.3 rc1
# 4 [python] Basics of functions
Basic knowledge of Python
Sober trivia of python3
Summary of Python arguments
Basics of python: Output
Installation of matplotlib (Python 3.3.2)
Application of Python 3 vars
Various processing of Python
[Python] Correct usage of map
Towards the retirement of Python2
Summary of python file operations
Summary of Python3 list operations
Python --Quick start of logging
Progress of 5/6 ~ C arrangement etc. ~
Recommendation of binpacking library of python
Automatic update of Python module
Python --Check type of values
[Python] Etymology of python function names
About the ease of Python
Static analysis of Python programs
About various encodings of Python 3
Equivalence of objects in Python
Introduction of activities applying Python
python> Handling of 2D arrays
Install multiple versions of Python
Version upgrade of python Anaconda
Handling of python on mac
python: Basics of using scikit-learn ①
2.x, 3.x character code of python
Comparison of 4 Python web frameworks
[python] super (), inheritance, __init__, etc.
Twitter posts on Python 3 etc.
Simple FPS measurement of python
Check OpenSSL version of python 2.6
Python implementation of particle filters
Post processing of python (NG)
[Python] Copy of multidimensional list
Faster loading of Python images
Sample usage of Python pickle
Basic usage of Python f-string
Implementation of quicksort in Python
[Python] Correct usage of join
About the features of Python