I use python but I don't know the class well, so I will do a tutorial

I use python, but I don't really understand class. But pytorch has a lot of classes, so I need to study.

I hope people in similar positions can use it to lower psychological barriers.

See Official Document 9: class for the correct understanding.

For the time being, the function "def"

You can specify a name and arguments for the operation you want to process.

def kakezan(a, b):
    return a*b

kakezan(9, 9)
81

The execution result can be saved in a variable as follows.

times99 = kakezan(9, 9)

Think about class with the simplest structure

Think of it as just a box with informational values

class keisan:
    num1=1
    num2=2

Information in the class can be retrieved using dot symbols.

keisan.num1

If you connect it with an argument and equal it, you can handle it as if you were transferring a box containing information.

box1 = keisan()
box1
<__main__.keisan at 0x7f5e03896b38>

The name of the class is output

box1.num1

The contents can be taken out with dots.

Rewrite the variable of the object called box1

box1.num1=10
box1.num1
10

constructor

A method (function in class) that is always executed when an object is created

class keisan:
    num1=1
    num2=2
    def __init__(self):
        print('Always displayed')

box3 = keisan()

If you put class in a variable, the constructor part will be executed

Always displayed

The above self is a magic to write If the target pointed by self is the above, box3 There is nothing to do right now, but be sure to include some arguments. Can also be used for instructions

class keisan:
    num1=1
    num2=2
    
    def __init__(self,name1,age1):
        print('The first name is' + name1 + 
                'And the age is' + str(age1) + 'is. This will be displayed every time.')

box4 = keisan()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-7-df434c06b06e> in <module>()
      7                 'And the age is' + str(age1) + 'is. This will be displayed every time.')
      8 
----> 9 box4 = keisan()

TypeError: __init__() missing 2 required positional arguments: 'name1' and 'age1'

If you do not enter anything, print cannot be executed and an error will occur.

box4 = keisan(name1='Mike',age1=19)
The first name is Mike and he is 19 years old. This will be displayed every time.

Display processing is finished.

The input cannot be retrieved as it is.

box4.name1
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-9-53236fb457a0> in <module>()
----> 1 box4.name1

AttributeError: 'keisan' object has no attribute 'name1'

Get an error If you want to save it, create an argument

class keisan:
    num1=1
    num2=2
    def __init__(self,name1,age1):
        self.name1=name1
        self.age1=age1
        print('The first name is'+name1+'And the age is'+str(age1)+'is. This will be displayed every time.')

box5 = keisan('Rachel',22)
box5.name1
Rachel

I was able to take it out.

When there is no argument but you want to perform a fixed process

class keisan:
    num1=1
    num2=2
    def __init__(self,val1):
        self.val1=val1
    def plus10(self):
        self.val1 +=10

box6 = keisan(val1=15)
box6.val1
15

Use the plus10 method in the class

box6.plus10()
box6.val1
25

Methods to modify objects in a class

Argument should be cls instead of self

class keisan:
    num2=2
    def __init__(self,val1):
        self.val1=val1
    def plus10(self):
        self.val1 +=10
    def plus5(cls):
        cls.num2 +=5

box7 = keisan(val1=22)
box7.num2
2

Execute plus5 of the method that changes num2 of class

box7.plus5()
box7.num2
7

I was able to change num2 in the class

I don't want you to change your manners

When designing a class and exposing the code to others, add the "_" symbol to the parts that you do not want to change in the design.

class keisan:

    def __init__(self,val1,val2):
        self._val1=val1 #I don't want you to change
        self.val2=val2 #You can change

box9 = keisan(10,20)
print(box9._val1)
print(box9.val2)
10
20
box9._val1 = 30
box9._val1
30

I can change it

Strengthen the feeling that I do not want you to change a little more

class keisan:

    def __init__(self,val1,val2):
        self.__val1=val1 #Strong feelings that I do not want you to change
        self.val2=val2 #You can change

box10 = keisan(10,20)
box10.__val1
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-15-68ebfca72338> in <module>()
      6 
      7 box10 = keisan(10,20)
----> 8 box10.__val1

AttributeError: 'keisan' object has no attribute '__val1'

Get an error I can no longer confirm.

If you really want to touch it, put "_class name" in between

Confirmation of class name

print(type(box10))
<class '__main__.keisan'>

The class name can be confirmed as keisan

box10._keisan__val1
10

It could be confirmed. _ Hidden more than one.

I'm not sure about the namespace

Namespace is a concept related to name-to-object mapping There is function 1 in module 1 (a group of functions. Image of a group of functions). Functions with the same name can be treated as different things with the same name unless they are defined in another module. Such functions are the names of functions in different namespaces and have no relation.

It seems to be so check

class cs1:
    def __init__(self,val1):
        self.val1=val1
    def cal1(self,val2):
        self.kekka = self.val1 * val2

class cs2:
    def __init__(self,val1):
        self.val1=val1
    def cal1(self,val2):
        self.kekka = self.val1 + val2

class1 = cs1(10)
class1.cal1(15)
print(class1.kekka)

class2 = cs2(10)
class2.cal1(15)
print(class2.kekka)
150
25

Even if the name of the same function is different, if it is a method of another class, another process will be performed.

that's all

Reference: python documentation 9. Classes

Recommended Posts

I use python but I don't know the class well, so I will do a tutorial
I tried to scrape YouTube, but I can use the API, so don't do it.
Python3 I don't know the balanced binary search tree, but I wish I had a sorted set.
python I don't know how to get the printer name that I usually use.
I don't know what HEIC is. But for the time being, let's use PNG!
How to use the __call__ method in a Python class
I didn't know how to use the [python] for statement
I made a function to crop the image of python openCV, so please use it.
Homework was a pain, so I do management accounting with Python
I made a segment tree with python, so I will introduce it
I don't know the value error
Every time I draw a graph with python, I check it, so I will summarize only the simplest usage
I want to do it with Python lambda Django, but I will stop
I didn't know the basics of Python
I wanted to use the find module of Ansible2, but it took some time, so make a note
I couldn't import the python module with VSCODE, but I could do it on jupyterlab, so I searched for the cause (2)
[Python, Scala] Do a tutorial for Apache Spark
I wrote a class in Python3 and Java
Python: Prepare a serializer for the class instance:
[Python] I will upload the FTP to the FTP server.
I did a little research on the class
The concept of reference in Python collapsed for a moment, so I experimented a little.
Don't take an instance of a Python exception class directly as an argument to the exception class!
I couldn't import the python module with VSCODE, but I could do it on juoyterlab, so I'm talking about finding the cause.
A python implementation of the Bayesian linear regression class
I wanted to use the Python library from MATLAB
Let's start Python from Excel. I don't use VBA.
A memo that I touched the Datastore with python
I made a python library to do rolling rank
I want to use the R dataset in python
How much do you know the basics of Python?
"Cython" tutorial to make Python explosive: Pass a C ++ class object to a class object on the Python side. Part ①
I made a class to get the analysis result by MeCab in ndarray with python
(Note) I'll do a Django tutorial. Even if I follow the site, it doesn't work.
I don't tweet, but I want to use tweepy: just display the search results on the console
I was in charge of maintaining the Fabric script, but I don't know.> <To those who