A Java programmer studied Python. (About functions (methods))

I'm a Java programmer who started studying Python with great momentum because I've run out of posts in Java. Click here for the study article on "if, for, while statements" two times before. Click here for the previous study article on "About molds".

Nowadays, I'm wondering if I should study Python instead of studying AWS qualifications. After all coding is fun, isn't it? (excuse I'm serious this week. (Maybe not

This time, I will study functions (methods).

Reference site

Operation check environment

Functions and methods

First, let's check the shape of the basic function (method). In Java

HelloMethodDemo1.java


static void hello() {
    System.out.println("Hello World!");
}
public static void main(String[] args) {
    hello();
}

With Python

HelloMethodDemo1.py


def hello():
    print('Hello World!')
hello()

The execution result is the usual

Hello World!

By the way, if you write with a pattern that returns,

HelloMethodDemo2.java


static String hello() {
    return "Hello World!";
}
public static void main(String[] args) {
    System.out.println(hello());
}

HelloMethodDemo2.py


def hello():
    return 'Hello World!'
print(hello())

Python is so stylish that Java looks like a verbose bad language. Python is faster than Java, which has been indebted for over three years. I'm about to lose the meaning of studying Java. (Overstatement

Difference between function and method

What is defined in the module is a function, and what is defined in the class is a method. So what we're writing above is a function. The method is

HelloMethodDemo3.py


class TestClass:
    #Method
    def hello(self):
        print('Hello World!')

I say something like this.

argument

There are many cases where you want to pass an argument to a function (method) for processing. In Java

AddDemo.java


static int add(int a, int b) {
    return a + b;
}
public static void main(String[] args) {
    System.out.println(add(1, 2));
}

With Python

AddDemo.py


def add(a, b):
    return a + b
print(add(1, 2))

The only difference from Java is the presence or absence of type declarations, so I could understand patterns with arguments without any problems.

Initial value of argument

In the Site (Python-izm) that I referred to this time, There was a description that the initial value can be set in the argument. The following is an excerpt from the reference site.

If you specify an initial value for the argument, you can omit it when calling the function.

I see. That's why I actually wrote it.

AddDemo2.py


def add(a, b=2):
    return a + b
print(add(1)) #Execution result: 3
print(add(1, 3)) #Execution result: 4

By the way, when I set it as the first argument, it failed with an error. The initial value could only be set for the last argument.

AddDemo3.py


#Example of error
def add(a=1, b):
    return a + b
print(add(2))
def add(a=1, b=2):
    return a + b

This feature is not available in Java. (It was quite a feature in PHP, C ++, C # and other languages. I've used PHP and C # but never seen it ...) This ... when is the best time to use it ...? ?? ?? There really isn't a scene where the Java brain is useful ...

When you want to set a variable length (tuple) for the argument

You can also set tuples etc. in the argument. Specifically, use * (asterisk).

ArgsDemo.py


def variable(*args):
    print(args)
variable('a', 'b', 'c')

The execution result is

('a', 'b', 'c')

Global and local variables

In Python Variables defined outside the function are ** global variables **, Variables defined within a function are called ** local variables **. ~~ * Same as Java ~~

When assigning to a global variable in a function, declare it as global before executing it. For reference only, no global declaration is required.

So, I tried to write it in code by imitating it. If it is an image in Java,

IncrementsDemo.java


public class Main {
    public static int count = 1;
    
    void increments() {
        System.out.println(count);
        count++;
        System.out.println(count);
    }
    public static void main(String[] args) throws Exception {
        Main main = new Main();
        main.increments();
    }
}

The execution result is

1
2

I wrote this in python.

IncrementsDemo.py


count = 1

def increments():
    print(count)
    global count
    count += 1
    print(count)

increments()

Let's run it.

Main.py:5: SyntaxWarning: name 'count' is used prior to global declaration
  global count

It's a warning, not an error, but \ (^ o ^) / Well, by googled this kind of thing, you can learn new things. (Second excuse

That's why I searched Google and excerpted from the first site that appeared. (As far as the sample code is seen, it is Python 2 series, but ...)

Note that names that indicate global variables in global statements must not be used as local variables first in the same code block. It means that there must not be local variables and global variables with the same name in one function.

Hey ~ _〆 (・ ∀ ・ *) So, this time, it seems that it is useless to declare global after referring to count with print immediately after the function.

So I tried to fix it as below.

IncrementsDemo.py


count = 1

def increments():
    global count
    count += 1
    print(count)
    
print(count)
increments()

Run again

1
2

Hmm, it's done. When using a global variable in a function, declare it global when assigning it. Not required when referencing global variables. It seems better to remember that.

class Main:
    def __init__(self):
        self.count = 1

    def increments(self):
        print(self.count)
        self.count += 1
        print(self.count)

    @staticmethod
    def main():
        main = Main()
        main.increments()

Main.main()

It's a big deal, so make a note of what you learned from the code above.

What does the underscore used for a function mean?

The underscore used in the function name has a decent meaning. The reference site is here.

If it is defined with two underscores, it does not receive external references. (Private in Java?) If it is defined with one underscore, it is customary not to refer to it from the outside, but it is actually accessible.

The reference site also describes how to use it properly. I have the impression that you may not be able to use it properly until you get used to it personally ...

What is @staticmethod?

This is called a decorator. I wrote it in the impression that comes out later, but even if I read various sites, I do not understand it well, so I will stop writing here ...

Lambda expression

Next, about the lambda expression. Java has been adopted since 8.

By the way, Java has a shape like this.

LambdaDemo.java


Hoge hoge = (name) -> {
  return "Hello " + name + "!";
};

I'm a fucking slug who hasn't mastered the lambda expression so much, so I want to master the lambda expression ...

Returning to the story, lambda expressions also exist in Python. Here is the result of using it by imitating it.

LambdaDemo.py


output = lambda name: 'Hello' + name + '!'
print(output('lambda'))

The execution result is

Hello lambda!

Is it easier to read than Java? I feel like. However, I saw some sample codes that I wanted to apply knitting, but I couldn't understand at all. Later, I think it's better to study harder ...

Iterator

In Java, it is an interface that processes elements in order with Map, List, etc. It's the one that uses next (), hasNext (), remove (), and so on.

In the case of Python, it seems to be used when processing elements such as lists, tables, and dictionaries in order.

The idea seems to be the same as Java. However, there is almost no time to explicitly write "Iterator" in Java. (Is it just me ...) What's more, Java 8 has added the Stream API, so why not use it more and more? I think.

In Java, I feel that I often write in the following form.

java::IteratorDemo.java


List<String> list = new ArrayList<>();
Collections.addAll(list, "Sun.", "Mon.", "Tues.", "Wed.", "Thurs.", "Fri.", "Sat.");

Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
  System.out.println(iterator.next());
}

java::IteratorDemo.java


List<String> list = new ArrayList<>();
Collections.addAll(list, "Sun.", "Mon.", "Tues.", "Wed.", "Thurs.", "Fri.", "Sat.");

for(Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {			 
    System.out.println(iterator.next());
}

(It feels like you can extend for statement as List!)

Execution result

Sun.
Mon.
Tues.
Wed.
Thurs.
Fri.
Sat.

What happens with Python?

IteratorDemo.py


week = ['Sun.', 'Mon.', 'Tues.', 'Wed.', 'Thurs.', 'Fri.', 'Sat.']
iter_week = iter(week)

for i in iter_week:
    print(i)

This overwhelmingly small number of input characters! I find it quite convenient to use the for statement to move on to the next iterator.

week = ['Sun.', 'Mon.', 'Tues.', 'Wed.', 'Thurs.', 'Fri.', 'Sat.']
for i in week:
    print(i)

By the way, like Java, you can also use the next function.

IteratorDemo.py


week = ['Sun.', 'Mon.', 'Tues.', 'Wed.', 'Thurs.', 'Fri.', 'Sat.']
iter_week = iter(week)

print(next(iter_week))
print(next(iter_week))
print(next(iter_week))
print(next(iter_week))
print(next(iter_week))
print(next(iter_week))
print(next(iter_week))

This will still behave the same as the execution result above. By the way, in the last element, when I used the next function again, I got the exception ** StopIteration **.

I haven't learned it yet, but it seems that there is also a try ~ except syntax.

generator

It's not in Java. It seems to be a relative of the iterator and a repeatable object. There are generator functions and generator expressions, and the generator function is called the generator. Generator functions can be achieved by using the yield keyword. To be honest, I don't really understand it, so I actually wrote it.

It mimics the sample Python-izm.

YieldDemo.py


def func():
    yield('Good morning')
    yield('Hello')
    yield('Good evening')

f = func()
print(next(f))
print(next(f))
print(next(f))

The execution result is

Good morning
Hello
Good evening

By the way, when I used the next function again, I got the exception ** StopIteration **.

The impression is that it is similar to the list.

The following is an excerpt from the explanation of Python-izm.

You can perform loop processing with> for etc., but the difference from the case of performing iterative processing with a list etc. is that the value is generated and returned as much as necessary each time.

This seems to have the advantage that generators consume less memory than lists. Also, when using a large amount of data, it seems better to use a generator than a list. (I'm a fucking small fish programmer, so I don't think I'll be indebted for the time being ...)

Impressions

This time I studied about functions (methods). Iterators and generators seem to be quite deep. Perhaps when I actually tried using it, I got the impression that it seemed to be quite difficult.

Besides, there was an introduction of the decorator (@), so I read the explanation + I googled the points I do not understand. As a result, I couldn't understand what I was saying at all, so I stopped writing about decorators this time. (Hey When I can understand it, I will add it to this article or post it as a new article.

Also, it would be nice to have a comparison between Python's comprehension and Java's Stream forEach processing + lambda.

I received a comment. Inclusive notation? ?? ?? I thought about it, but I was confused, "What is this ... inclusion? Extension? I don't know how it works ...". It seems that those who can't write comprehensions using Python are useless. I don't know if it's true (hey I'm thinking of adding this to this article or posting it as a new article together with the decorator.

Recommended Posts

A Java programmer studied Python. (About functions (methods))
A Java programmer studied Python. (About type)
A Java programmer studied Python. (About the decorator)
A Java programmer studied Python. (for, if, while statement)
[Python] Memo about functions
A story about modifying Python and adding functions
A memorandum about correlation [Python]
A memorandum about Python mock
A note about [python] __debug__
[python] Manage functions in a list
Python: A Note About Classes 1 "Abstract"
About python dict and sorted functions
Dynamically define functions (methods) in Python
A note about mock (Python mock library)
[Python3] I made a decorator that declares undefined functions and methods.
A little more about references ~ Using Python and Java as examples ~
Python functions
A story about Python pop and append
About February 02, 2020 * This is a Python article.
I wrote a class in Python3 and Java
Why I'm a Java shop and start Python
A note on optimizing blackbox functions in Python
A memo about writing merge sort in Python
A note about the python version of python virtualenv
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
A memorandum about the Python tesseract wrapper library
About python slices
About python comprehension
About Python tqdm.
About python yield
About python, class
About Go functions
About python inheritance
About python, range ()
About python decorators
#Python basics (functions)
[Beginner] Python functions
About python reference
About Python decorators
Python Easy-to-use functions
[Python] About multi-process
Python basics: functions
A story about making 3D space recognition with Python
Write about building a Python environment for writing Qiita Qiita
Python points from the perspective of a C programmer
A story about making Hanon-like sheet music with Python
A story about trying a (Golang +) Python monorepo with Bazel
A note on handling variables in Python recursive functions
Python: Get a list of methods for an object
A memo about building a Django (Python) application with Docker
A reminder about the implementation of recommendations in Python