This and that of python properties

Introduction

I didn't understand python's "property", so I would like to summarize what I have researched.

What is a property in the first place?

[Easy Python](https://www.amazon.co.jp/%E3%81%8B%E3%82%93%E3%81%9F%E3%82%93-Python-%E3%83%97 % E3% 83% AD% E3% 82% B0% E3% 83% 9F% E3% 83% B3% E3% 82% B0% E3% 81% AE% E6% 95% 99% E7% A7% 91% E6 % 9B% B8-% E6% 8E% 8C% E7% 94% B0-% E6% B4% A5% E8% 80% B6% E4% B9% 83 / dp / 4774195782)

I want to manage values well, but I also want to be able to access values naturally like instance variables. "Properties" is the best of both worlds.

Is written. The point is that you can't easily change the value from the outside, and you should think that it is useful when you want to take it out easily.


def property name(self):
processing

'Define a method to retrieve the value of a property'
@property
def property name(self):
return value
  
'Set the value of the property'
@Property name.setter
def property name (self, value)
Processing to set the value

Properties are defined like this.


@property

When you see it, please think "Hi! I came!".

What are instance variables?

Properties are related to instance variables, so we will discuss instance variables here. Instance variables are variables that exist independently for each instance that is created when the class is executed. It's a little difficult, isn't it?


def __init__(self, message):
    self.message = message #Instance variable message

This "self.message" is an instance variable. Next, let's look at the overall definition and movement.

#Instance variables

class MyClass:
    def __init__(self, message):  #Initialization: Called automatically when creating an instance
        self.message = message    #Declare the instance variable message

    def print_message(self):  #A function that displays the value of the instance variable message
        print(self.message)  #Access and display the instance variable message


instance = MyClass("instance")  #Create instance instance
python = MyClass("python")  #Create instance python

print(instance.message)  #Displayed as instance
print(python.message)  #Displayed as python

instance.print_message()  #Displayed as instance
python.print_message()  #Displayed as python

instance.message = 'Python' #self.Change the content of message to "Python"
print(instance.message)  #Shown as Python=What was previously displayed as "instance" has been changed

As you can see in the code above, you can easily retrieve the value, but you can easily change it. If you can make changes easily, unexpected things such as making mistakes will occur. As I said earlier, properties are properties that can be easily retrieved with good management of changes.

Let's deepen your understanding by referring to the usage examples.

Property utilization example


class PropertyClass:
      def __init__(self, msg):
        self.message = msg
  
      def __str__(self):
        return self.message
    
      @propaty
      def message(self):
        return self.__message
    
      @message.setter
      def message(self, value):
        if value != '':
          self.__message = value
      
pc= PropertyClass('Hello')   #  ①
print(pc.messsage)   #Hello ②
pc.message = ''     #Change the content of message from "Hello" to an empty string ③
print(pc)           # Hello  ④
pc.message = 'Bye!' #Change the contents of the message from "Hello" to "Bye"!⑤
print(pc)       #Bye!   ⑥

Pass "Hello" as an argument in ①, and the content of "self.message" becomes "Hello". (2) When the message method is called, "Hello" is returned as the return value. (3) The value of "message" has been changed to an empty string. ④ You should have changed it to an empty string in ③, but "Hello" is displayed again. I wonder why? When setting a new value, the procedure is first performed at "@ message.setter".


if value != '':
          self.__message = value

This time, I am saying that I will accept changes when it is not an empty string like this. Therefore, the empty string was rejected and "Hello" was displayed. ⑤ I will try to change to "Bye!" Next time without discipline. ⑥ This time it is not an empty string, so the change was allowed.

Also, this time, it will not be directly accessed from the outside as "message". Please keep in mind that items with two _ such as "" cannot be accessed from the outside.

The point is that when you set a new value like this, you can control it so that unexpected things do not enter.

You should have understood the general movement in this chapter. Let's take a closer look in the next chapter.

Property and setter movement

Let's deepen our understanding by checking how the part with property and setter is called.


class Myclass:
    def __init__(self, input_name):
        self.hidden_name = input_name

    @property
    def name(self):
        print('inside the getter')
        return self.hidden_name

    @name.setter
    def name(self, input_name):
        print('inseide the setter')
        self.hidden_name = input_name


mc = Myclass('Hello') #Pass "Hello" as an argument ①
print(mc.name)     #'Hello'Displayed as+ 'inside the getter'Displayed as ②
mc.name = 'Python'    #The value'Python'change to+ 'inside the setter'③
print(mc.name)        #'Python'Displayed as+ 'inside the getter'Displayed as ④

As you can see from the fact that'inside the getter'is displayed in ②, you can see that'@prperty' is being called. On the other hand, when changing the value in ③,'@ name.setter' is called as it says'inside the setter'. As a result, the value is changed normally in ④.

As you can see from this,'@property' is called when calling a value, and'@ 〇〇.setter' is called when changing a value. And you can limit the value with'setter'to prevent unexpected values from entering. As you may have noticed, it's easy to call because you don't need a'()'at the end of the call.

Finally

This time I have explained about properties. I wonder if it will be easier to understand if you recognize that it is easy to call and set the value exactly. We will continue to update the articles in the future. Also, if you have time, please take a look at other articles.

Recommended Posts

This and that of python properties
This and that of the inclusion notation.
matplotlib this and that
This and that using reflect
Zabbix API this and that
Source installation and installation of Python
Environment construction of python and opencv
The story of Python and the story of NaN
Installation of SciPy and matplotlib (Python)
This and that learned from boost.python
Coexistence of Python2 and 3 with CircleCI (1.0)
This and that using NLTK (memo)
Summary of Python indexes and slices
This and that for using Step Functions with CDK + Python
Reputation of Python books and reference books
[Notes / Updated from time to time] This and that of Azure Functions
Verification of the theory that "Python and Swift are quite similar"
Installation of Visual studio code and installation of python
(Bad) practice of using this in Python
Extraction of tweet.js (json.loads and eval) (Python)
Connect a lot of Python or and and
Easy introduction of python3 series and OpenCV3
[Python] Various combinations of strings and values
Idempotent automation of Python and PyPI setup
Full understanding of Python threading and multiprocessing
Project Euler # 1 "Multiples of 3 and 5" in Python
Introduction of Python
Basics of Python ①
Basics of python ①
Copy of python
"Manim" that can draw animation of mathematical formulas and graphs with Python
Introduction of Python
Correspondence summary of array operation of ruby and python
Summary of the differences between PHP and Python
The answer of "1/2" is different between python2 and 3
A nice nimporter that connects nim and python
Development of games that take advantage of quantum properties
Specifying the range of ruby and python arrays
Installation of Python3 and Flask [Environment construction summary]
Compare the speed of Python append and map
[Python] Chapter 02-01 Basics of Python programs (operations and variables)
This is the only basic review of Python ~ 1 ~
This is the only basic review of Python ~ 2 ~
Implementation of TRIE tree with Python and LOUDS
python development environment -use of pyenv and virtualenv-
Links and memos of Python character code strings
Simple comparison of Python libraries that operate Excel
Comparison of R and Python writing (Euclidean algorithm)
This is the only basic review of Python ~ 3 ~
I / O related summary of python and fortran
List of Python code to move and remember
This and that useful when used with nohup
One-liner that outputs 10000 digits of pi with Python
[Python] A rough understanding of iterators, iterators, and generators
About the * (asterisk) argument of python (and itertools.starmap)
A discussion of the strengths and weaknesses of Python
About shallow and deep copies of Python / Ruby
Continuation of multi-platform development with Electron and Python
Explanation of edit distance and implementation in Python
[Python] Class type and usage of datetime module
Example of reading and writing CSV with Python