Python functions

I will summarize what I learned about python functions.

function

A function is a collection of processes. It is used to make the process easier to understand in order to extract similar processes, standardize them, and code them efficiently. By the way, in python, it seems customary to declare function names separated by "_".

Definition method

The definition method in python is defined as "def function name ():". The processing in the function is described by shifting the indent. Also, if you want to set an argument, describe it in ().

python


#No arguments
def test_function_1():
    pass

#With arguments
def test_function_2(arg1, arg2):
    pass

It looks like this in java.

java


//No arguments
void testFunction1() {
}

//With arguments
void testFunction2(String arg1, String arg2) {
}

How to call

The java call method is the same in python. It can be executed with the function name ().

python


def test_function_1():
    print("The function has been executed.")

def test_function_2(arg1):
    print("arg1:" + arg1)

#Execute function
test_function_1() #⇒ The function has been executed.
test_function_2("I passed an argument.") # ⇒ arg1:I passed an argument.
print(test_function_1()) #⇒ The function has been executed. None

java


//No arguments
void testFunction1() {
    System.out.println("The function has been executed.");
}

void testFunction2(String arg1) {
    System.out.println("arg1:" + arg1);
}

//Execute function
testFunction1(); //⇒ The function has been executed.
testFunction2("I passed an argument."); // ⇒ arg1:I passed an argument.

If you do not define a return value, the function will return None. If you want to define a return value, write "return return value" at the end of the function.

python


def test_function_3():
    return "Try to return the return value"

#Execute function
print(test_function_1()) #⇒ Try to return the return value

Since it is the same in java, it will be omitted.

Default value

You can set default values for python arguments. By setting, the function can be executed without specifying an argument with default values. In that case, the default value will take effect.

python


def test_function_3(arg1, arg2 = "No arguments"):
    print("arg1:" + arg1 + " arg2:" + arg2)

#Execute function
test_function_3("Argument 1") # ⇒ arg1:Argument 1 arg2:No arguments
test_function_3("Argument 1", "Argument 2") # ⇒ arg1:Argument 1 arg2:Argument 2

java does not have a feature like the default value.

Variadic argument

If you want to receive variadic arguments in python, define the function by prefixing the argument name with "". The received result can be used in the function as a tuple. By convention, variadic arguments are named " args". However, since it is a convention, it works even if it is not named args.

python


def test_function_4(*kahen):
    print(kahen)

test_function_4("Variable 1", "Variable 2", "Variable 3") # ⇒ ('Variable 1', 'Variable 2', 'Variable 3')

It can also be used with regular arguments.

python


def test_function_5(arg1, arg2, *kahen):
    print("arg1:" + arg1 + " arg2:" + arg2 + " kahen:" + str(kahen))

test_function_5("Invariant 1", "Invariant 2", "Variable 3", "Variable 4") # ⇒ arg1:Invariant 1 arg2:Invariant 2 kahen:('Variable 3', 'Variable 4')

In Java, write "..." after the type like String ...

java


//No arguments
void testFunction4(String... kahen) {
    System.out.println(Arrays.toString(kahen));
}

void testFunction5(String arg1, String arg2, String... kahen) {
    System.out.println("arg1:" + arg1 + " arg2:" + arg2 + " kahen:" + Arrays.toString(kahen));
}

//Execute function
testFunction4("Variable 1", "Variable 2", "Variable 3"); // ⇒ [Variable 1, Variable 2, Variable 3]
testFunction5("Invariant 1", "Invariant 2", "Variable 3", "Variable 4"); // ⇒ arg1:Invariant 1 arg2:Invariant 2 kahen:[Variable 3, Variable 4]

Decorator

Decorators are python-specific features that don't exist in Java. A function that takes a function as an argument and sets the function as a return value. It's hard to understand with words alone, so I'll write it.

Python


def deco(argFun):
    def retFun(arg):
        print("--Start--argument:" + arg)
        argFun(arg)
        print("--End--")
    return retFun

def test_function_6(arg):
    print("Decolated argument:" + arg)

deco(test_function_6)("TEST")

# --Start--argument:TEST
#Decolated argument:TEST
# --End--

It defines the decorator function "deco". This function returns the function "retFun". "RetFun" is a function that outputs a log before and after the execution of the function received by "deco". In this way, the decorator is a function that adds (decorates) processing before and after executing the function "test_function_6". Other than this, you can decorate using the "@" modifier.

Python


def deco(argFun):
    def retFun(arg):
        print("--Start--argument:" + arg)
        argFun(arg)
        print("--End--")
    return retFun

@deco
def test_function_7(arg):
    print("Decolated@argument:" + arg)

test_function_7("test")

# --Start--argument:test
# Decolated@argument:test
# --End--

This is the end of the explanation of the function. The idea of decorators is a very new learning experience for me as a Java enthusiast. It's hard to think of a good way to use it, but depending on how you use it, the code may be very confusing, so I'd like to think carefully when using it.

Recommended Posts

Python functions
#Python basics (functions)
[Beginner] Python functions
Python Easy-to-use functions
Python basics: functions
Python basic course (12 functions)
[Python] Memo about functions
# 4 [python] Basics of functions
Python built-in functions ~ Zip ~
Wrap Python built-in functions
Python> lambda> tiny functions / callback functions
Getting Started with Python Functions
Python3 programming functions personal summary
Study from Python Hour3: Functions
Overriding library functions in Python
Keyword arguments for Python functions
Python for super beginners Python #functions 1
Paiza Python Primer 7: Understanding Functions
Python 3 sorted and comparison functions
Python functions learned in chemoinformatics
Python higher-order functions and comprehensions
kafka python
Python control syntax, functions (Python learning memo ②)
Python basics ⑤
python + lottery 6
Python Summary
Python comprehension
Python technique
Azure Functions: Try Durable Functions for Python
Studying python
Python memorandum
Python FlowFishMaster
[python] Manage functions in a list
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
About python dict and sorted functions
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
Python2 + word2vec
"Effective Python 2nd Edition" Chapter 3 <Functions>
[Python] Variables
Python sys.intern ()