[Introduction to Data Scientists] Basics of Python ♬ Functions and classes

Continuing from last night's [Introduction to Data Scientists] Python Basics ♬ Functions and Anonymous Functions, etc., we will talk about functions and classes. 【Caution】 ["Data Scientist Training Course at the University of Tokyo"](https://www.amazon.co.jp/%E6%9D%B1%E4%BA%AC%E5%A4%A7%E5%AD%A6%E3 % 81% AE% E3% 83% 87% E3% 83% BC% E3% 82% BF% E3% 82% B5% E3% 82% A4% E3% 82% A8% E3% 83% B3% E3% 83 % 86% E3% 82% A3% E3% 82% B9% E3% 83% 88% E8% 82% B2% E6% 88% 90% E8% AC% 9B% E5% BA% A7-Python% E3% 81 % A7% E6% 89% 8B% E3% 82% 92% E5% 8B% 95% E3% 81% 8B% E3% 81% 97% E3% 81% A6% E5% AD% A6% E3% 81% B6 % E3% 83% 87% E2% 80% 95% E3% 82% BF% E5% 88% 86% E6% 9E% 90-% E5% A1% 9A% E6% 9C% AC% E9% 82% A6% I will read E5% B0% 8A / dp / 4839965250 / ref = tmm_pap_swatch_0? _ Encoding = UTF8 & qid = & sr =) and summarize the parts that I have some doubts or find useful. Therefore, I think the synopsis will be straightforward, but please read it, thinking that the content has nothing to do with this book.

Forward swing

This chapter focuses on the mechanism of python function calls and the differences between class notation and functions. For the mechanism of function call, refer to the following. 【reference】 Module function call @PyQ

Chapter1-2 Python Basics

1-2-6 Class and instance

Create an instance from the class. We'll leave this book a bit to show the similarities between function calls, class declarations, and instance execution.

Function call

Functions are sometimes used in one PG, but when trying to write a complicated PG, the function is saved and used as a Package with a structured directory structure. In that case, python has an important mechanism. That is, if you execute the following code with > python calc_add.py, it will work in the following order. ① Two function definitions are made ② The module name calc_add is assigned to __name__ ③ The print statement is executed ④ The ʻif statement is True, and the following two print` statements are executed.

calc_add.py


def calc_add(a, b):
    return a + b
    
def calc_multi(a, b):
    return a * b
       
print('__name__:', __name__)

if __name__ == '__main__':        
    print(calc_add(5,3))
    print(calc_multi(5, 3))

result

__name__: __main__
8
15

Run from other code main.py

In this case, run > python main.py (1) Read the two functions calc_add and calc_multi from calc_add.py by the first declaration statement. At this time, as you can see from the output, the above calc_add.py is executed, the print statement is executed, and __name__: calc_add is output. ʻIf statement is False (__ name__ = calc_add), so it will not be executed ② Next, the print statement of main.py is executed. ③ Since the ʻif statement of main.py is True, the following two print statements are executed. With this mechanism, you can call a function and use it. ④ Therefore, it is necessary to include the notation ʻif name =='main':`. However, it is not essential when calling and using it.

main.py


from calc_add import calc_add, calc_multi

print('__name__2:', __name__)

if __name__ == '__main__':   
    print(calc_add(5,3))
    print(calc_multi(5, 3))

result

__name__: calc_add
__name__2: __main__
8
15

** Note) print ('__ name__:', __name__) is included to explain the mechanism and is not usually required ** class The class looks the same as the function. However, declare class. Then, as you can see in the if statement, the class defines the instance and then calls and uses the function defined in the class. This mechanism is called object-oriented. That is, it is a mechanism that generates many instances from class and executes them. The features of the class definition are as follows. ① Declare class (2) Define the constructor def __init __ (self, x, y):. The variable self is mandatory and defined (the variable self is special, but it took me a while to think it was just one of the variables). The arguments x and y define what is needed at any given time. 【reference】 What is Python self? Explanation of usage and precautions

About self
-Self is not described as an argument when declaring instance
・ Self is a class variable
・ Can be used for class inheritance
-If both the class variable and the instance variable have values, the instance variable is given priority for reference.

③ Constructor def __init __ (self, x, y): is the code that works first when the instance of the class is defined. ④ Define other necessary functions. ⑤ Execute necessary processing like ʻinstance.calc_add () ⑥ ʻif __name__ =='__main__': is written for the same reason as the function, but it is not essential when calling and using it, so many classes do not have this if statement or execution statement. ** Note) print ('__ name__:', __name__) is included to explain the mechanism and is not usually required **

calc_class.py


class MyCalcClass:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        
    def calc_add1(self, a, b):
        return a + b

    def calc_add2(self):
        return self.x + self.y
  
    def calc_multi(self, a, b):
        return a * b
        
print('__name__:', __name__)
if __name__ == '__main__':        
    instance_1 = MyCalcClass(1,2)
    instance_2 = MyCalcClass(5,10)
    print(instance_1.calc_add1(5,3))
    print(instance_1.calc_add2())
    print(instance_1.calc_multi(5, 3))
    instance_1.calc_print(5)

>python calc_class.py result It is as follows, but you can see that the result is calculated depending on the initial value of instance1. If the if statement part is deleted, only __name__: __main__ is output.

__name__: __main__
8
3
15
data:5:Value of y 2

Run from other code main.py

main_class.py


from calc_class import MyCalcClass

print('__name__2:', __name__)

if __name__ == '__main__':
    instance_1 = MyCalcClass(1,2)
    instance_2 = MyCalcClass(5,10)
    print(instance_1.calc_add1(5,3))
    print(instance_1.calc_add2())
    print(instance_1.calc_multi(5, 3))
    instance_1.calc_print(5)

result >python main_class.py Of course, the result is the same as ↑. However, as with the function, __name__: calc_class is output. That is, the name of the called file is entered in __name__, and __main__ is entered in the case of itself.

__name__: calc_class
__name__2: __main__
8
3
15
data:5:Value of y 2

Summary

・ I compared the function call and the class. -Define a class, call it, and execute the instance

・ It's just before writing general python code ・ This book ends the basics of python in this section, but the missing parts will be supplemented in future sections (in a sense, this book will continue to explain the code using various Lib of python).

Recommended Posts

[Introduction to Data Scientists] Basics of Python ♬ Functions and classes
[Introduction to Data Scientists] Basics of Python ♬ Functions and anonymous functions, etc.
[Introduction to Data Scientists] Basics of Python ♬
[Introduction to Data Scientists] Basics of Python ♬ Conditional branching and loops
[Introduction to Data Scientists] Basics of Probability and Statistics ♬ Probability / Random Variables and Probability Distribution
# 4 [python] Basics of functions
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
[Introduction to Data Scientists] Basics of scientific calculation, data processing, and how to use graph drawing library ♬ Basics of Scipy
[Introduction to Data Scientists] Basics of scientific calculation, data processing, and how to use graph drawing library ♬ Basics of Pandas
[Introduction to Data Scientists] Basics of scientific calculation, data processing, and how to use graph drawing library ♬ Basics of Matplotlib
List of Python libraries for data scientists and data engineers
[Introduction to cx_Oracle] (Part 6) DB and Python data type mapping
[Introduction to Data Scientists] Descriptive Statistics and Simple Regression Analysis ♬
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Data Scientists] Basics of scientific calculation, data processing, and how to use the graph drawing library ♬ Environment construction
[Python] Summary of how to use split and join functions
[Introduction to Python] Summary of functions and methods that frequently appear in Python [Problem format]
Comparison of how to use higher-order functions in Python 2 and 3
[Introduction to Python] Combine Nikkei 225 and NY Dow csv data
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part1-
Introduction to Python Basics of Machine Learning (Unsupervised Learning / Principal Component Analysis)
[Introduction to Python] I compared the naming conventions of C # and Python.
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part2-
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part4-
[Introduction to Udemy Python3 + Application] 69. Import of absolute path and relative path
[Introduction to Udemy Python3 + Application] 12. Indexing and slicing of character strings
Introduction to TensorFlow-Summary of four arithmetic operations and basic mathematical functions
[Introduction to cx_Oracle] (Part 2) Basics of connecting and disconnecting to Oracle Database
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part3-
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
Bind methods to Python classes and instances
[Introduction to Udemy Python3 + Application] 55. In-function functions
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
Compress python data and write to sqlite
Easy introduction of python3 series and OpenCV3
Introduction of Python
Basics of Python ①
#Python basics (functions)
Python basics: functions
Introduction of Python
[Introduction to Udemy Python 3 + Application] 26. Copy of dictionary
[Introduction to Udemy Python 3 + Application] 19. Copy of list
[Introduction to cx_Oracle] (Part 3) Basics of Table Reference
[Python] How to read data from CIFAR-10 and CIFAR-100
[Introduction to Python3 Day 22] Chapter 11 Concurrency and Networking (11.1 to 11.3)
[Introduction to Python] How to handle JSON format data
[Introduction to Udemy Python3 + Application] 64. Namespace and Scope
[Python] Chapter 02-01 Basics of Python programs (operations and variables)
[Introduction to cx_Oracle] (5th) Handling of Japanese data
List of Python code to move and remember
[Python for Hikari] Chapter 09-01 Classes (Basics of Objects)
cv2 functions and data types (OpenCV python bindings)
[Introduction to Python] Basic usage of lambda expressions
[Python] From morphological analysis of CSV data to CSV output and graph display [GiNZA]
[Introduction to cx_Oracle] (Part 9) DB and Python data type mapping (version 8 or later)
Python basics basic course CSV processing (functions and classes, part 1 CSV is read and written)
[Introduction to Python] How to get the index of data with a for statement
Basics of Python scraping basics