A Java programmer studied Python. (About the decorator)

I'm a Java programmer who started studying Python with great momentum because I've run out of posts in Java.

This time, I'll study the decorators that I didn't understand last time and omitted. Click here for past study articles. About if, for, while statements About type (About functions (methods)

What is a decorator?

In Samurai Engineer School, it was written as follows.

A decorator is a function for adding or changing processing to an existing function.

Decorators allow you to add or change functionality to existing functions without having to directly modify them.

For example, if you have a function and you want to change the behavior of the function by processing, you can save the trouble of creating a similar function for each processing.

Is it an override in Java? Overriding is like redefining or recreating a method, so is it a bit different from adding or changing?

How to use?

The basic syntax is

@Decorator name

In Java, @ is used like an annotation. I looked at some sample code, but all of them were defined on top of the function (def).

The following is a copy of the sample code from here.

def decorateSample(myfunc):
    print("Hello Decorator")
 
@decorateSample
def myfunc():
    print("Test")

When I did this, I got the output "Hello Decorator". By the way, "Test" is not output. The point is to set the name of the function that uses the decorator as an argument.

pass means "do nothing". Is it ";" or "return;" in Java?

This is one of the syntaxes called syntactic sugar. ~~ It's a delicious name. ~~ I was new to the word syntactic sugar, so I derailed a little, but I looked it up.

What is syntactic sugar?

There was a normal page on Wikipedia. I thought it was a Python-specific syntax name, but it wasn't.

It is something that can be written in a simpler and easier-to-understand way that has exactly the same meaning as a complicated and difficult-to-understand way of writing.

It seems that the syntax is abbreviated. So, if you express it in Java,

//Writing that is not syntactic sugar
String[] strs = new String[2];
strs[0] = "abc";
strs[1] = "def";
//Syntax sugar writing
String[] strs = {"abc", "def"};

about it. The fact that "Hello Decorator" is output even though the function is not called is syntactic sugar. I'm embarrassed I didn't know ...

What is the decorator doing internally?

The Python code mentioned above is, after all,

def decorateSample(myfunc):
    print("Hello Decorator")
 
def myfunc():
    print("Test")

myfunc = decorateSample(myfunc)

Seems to be doing.

myfunc = decorateSample(myfunc)

What are you doing here? ?? Assign the contents of the decorateSample function to myfunc? Replacement? Do you feel like you are doing it? So, does it mean that "Test" is not output and "Hello Decorator" is output? ~~ I've been frustrated by my lack of understanding ~~

Python standard decorator

Python comes with standard decorators. There are three types of commonly used decorators:

Let's look at each one.

classmethod

The reference was here.

A class method is a method defined within a class that can be called without instantiation. This is used when defining a method that does something with the class itself, not the instance.

Mmm ... Before I looked it up, I thought "Java instance method" = "Python class method", but it seems different.

The usual way to write a method in Python is the image below (instance method in Java?)

class SampleClass:
    def hello_world(self):
        print("Hello World!")

#Instantiate and call a method
sample_class = SampleClass()
sample_class.hello_world()

What is self! However, it seems that it means "this" in Java.

Now you can use @classmethod to call it without having to instantiate it as above.

class SampleClass:
    
    @classmethod
    def hello_world(cls):
        print("Hello World!")

#Method call as it is
SampleClass.hello_world()

It's customary to change self to cls. Note that the name of the first argument is different between the normal method and the class method. (Since the class method receives the class as the first argument, it seems to be named cls ...)

It seems that the class method can be realized by using the classmethod () function, but it is not recommended. So I omitted this time.

staticmethod

Same as classmethod, quoted from this site.

Briefly speaking, there are the following differences. -Staticmethod: This works regardless of the class even if it is defined in the class, and considers only the received arguments. Roughly speaking, it's just a function. -Classmethod: This can take the class itself as an argument and use it with the received argument

The staticmethod seems to be a method that doesn't require instantiation and doesn't take any arguments. "That's it. Then you can use a normal function. When should I use it?"

Apparently the behavior in the inherited class is different. Below is another code that mimics the sample code.

class ParentClass():
    str = 'Hello, I am Parent Class'
 
    @classmethod
    def class_method(cls):
        print('class_method: ' + cls.str)
 
    @staticmethod
    def static_method():
        print('static_method: '+ ParentClass.str)

class ChildClass(ParentClass):
    str = 'Hello, I am Child Class'

ChildClass.class_method() #Execution result: class_method: Hello, I am Child Class
ChildClass.static_method() #Execution result: static_method: Hello, I am Parent Class

Even if the child class calls static_method (), it still calls the parent class. The classmethod changes to the reference destination when inheritance is performed. I want to use staticmethod when the behavior does not change even in child classes. It seems that.

Java also has a name called static method, but it seems that you need to be careful because the behavior when inheriting is different.

property

Also quoted from Reference Site.

Python classes can usually read and write directly to properties (attributes). Self is set as an argument of the init method that is executed when the class is created, isn't it? A property is a variable in the form of "self. ~". With @property, the function decorated with this decorator becomes a getter, a readable property. Being able to read only means that you cannot change new values.

What? (´ ・ ω ・ `)? I thought, I reread it about 5 times.

Is it a decorator used only for getters? getter is Java

public String getter() {
  return this.hoge;
}

Something like that? e? So what about the setter decorator?

What is the init method! When I looked it up, it was a ** constructor **. I see.

So, let's see it again,

class SampleClass(object):
    def __init__(self, hoge):
        self.__hoge = hoge
    
    @property
    def getter(self):
        return self.__hoge

#Instantiate and call a method
sample_class = SampleClass(1234)
x = sample_class.getter

print(x) #Execution result: 1234

So, the setter I was interested in was

class SampleClass(object):
    def __init__(self, hoge):
        self._hoge = hoge
    
    @property
    def hoge(self):
        return self._hoge
    
    @hoge.setter
    def hoge(self, hoge):
        self._hoge = hoge

#Instantiate and call a method
sample_class = SampleClass(1234)
x = sample_class.hoge

print(x) #Execution result: 1234

sample_class.hoge = 5678
x = sample_class.hoge

print(x) #Execution result: 5678

It is important to match the method name with the one with @property, which is a getter. (I didn't understand that and was quite addicted to it ...) Create it with a name such as @propertyname.setter.

Impressions

I understand it as a concept, but I don't know how to use it well. I think it's probably because I don't understand the detailed behavior.

If there is no function similar to Java, I'm worried that my understanding will drop. I didn't have much trouble with PHP and C #, so I'm a little disappointed ... or rather frustrated ...

I'm doing an IT technical book fair on Amazon, so I'll buy a good Python book. For now, I'm wondering if it's easy to read if it's a web application or game programming.

"Stop it!" "I don't need a book! The website is enough!" If you have an opinion such as "If you are a beginner, this is definitely this book!", I would appreciate it if you could let me know.

Reference site

https://www.sejuku.net/blog/25130 http://st-hakky.hatenablog.com/entry/2017/11/15/155523 https://kiwamiden.com/how-to-use-property-decorator http://nametake-1009.hatenablog.com/entry/2015/10/21/222829

Recommended Posts

A Java programmer studied Python. (About the decorator)
A Java programmer studied Python. (About type)
A Java programmer studied Python. (About functions (methods))
A Java programmer studied Python. (for, if, while statement)
[Python] What is @? (About the decorator)
Thinking about logging, then
A Java programmer studied Python. (About type)
A note about the python version of python virtualenv
A memorandum about the Python tesseract wrapper library
Python points from the perspective of a C programmer
A reminder about the implementation of recommendations in Python
About the Python module venv
About the ease of Python
About the enumerate function (python)
A memorandum about correlation [Python]
A memorandum about Python mock
About the features of Python
A note about [python] __debug__
A note about hitting the Facebook API with the Python SDK
Python: A Note About Classes 1 "Abstract"
[Python] Make the function a lambda function
Create a Python general-purpose decorator framework
About the basics list of Python basics
A note about mock (Python mock library)
A little more about references ~ Using Python and Java as examples ~
[Python3] Define a decorator to measure the execution time of a function
After researching the Python library, I understood a little about egg.info.
Create a Python function decorator with Class
[Python Kivy] About changing the design theme
Write the test in a python docstring
About the virtual environment of python version 3.7
Search the maze with the python A * algorithm
Learn the design pattern "Decorator" in Python
Run the Python interpreter in a script
[Python] Summarize the rudimentary things about multithreading
[python] [meta] Is the type of python a type?
A story about Python pop and append
The story of blackjack A processing (python)
[Python] A progress bar on the terminal
[Python] A program that rounds the score
About February 02, 2020 * This is a Python article.
A note about doing the Pyramid tutorial
[Python] Get the files in a folder with Python
Created a Python wrapper for the Qiita API
Get the caller of a function in Python
ffmpeg-Build a python environment and split the video
I wrote a class in Python3 and Java
Make a copy of the list in Python
Why I'm a Java shop and start Python
About the difference between "==" and "is" in python
A memo about writing merge sort in Python
Python: Prepare a serializer for the class instance:
Data analysis in Python: A note about line_profiler
A story about running Python on PHP on Heroku
Think about building a Python 3 environment in a Mac environment
[Note] About the role of underscore "_" in Python
About the behavior of Model.get_or_create () of peewee in Python
[Python] A rough understanding of the logging module
Output in the form of a python array
A note about the new style base class
A python amateur tries to summarize the list ②
[Python] Find the transposed matrix in a comprehension