Reference site: [Introduction to Python] How to use class in Python?
Python is a language that supports object-oriented programming. To do this, you need to define and create a class. Python class definitions are easier than in other languages.
This time, I will explain how to handle basic classes in Python.
Python uses class statements to define classes. The definition method using the class statement is as follows.
class class name:
After the class statement, add the class name that will be the name of the class, and add ":" at the end. After that, add a paragraph indent and define the class.
class Test:
pass #Enter pass for a class that does nothing
test = Test() #Create an instance
You can define methods in the class. The method is defined as follows.
class class name:
def method name(self):
#Method definition
A method always has one or more arguments. Also, the first of the arguments is supposed to be named self. To call the method:
instance.Method name()
class Test:
def test_print(self):
print('This is test')
test = Test() #Instance generation
test.test_print() #Method call
Execution result
This is test
Among the methods, the method that is automatically called when an instance is created is called a constructor. To define the constructor, create a method named "init".
class Test:
def __init__(self,Argument 1,Argument 2, ….):
#Constructor definition
init also always requires the argument self. Other arguments can be attached, and the arguments are passed when calling the class when creating an instance.
class Test:
def __init__(self, num):
self.num = num; #Store the argument in the "num" variable of this class
def print_num(self):
print('The number passed as an argument is{}is.'.format(self.num))
test = Test(10) #The argument passed here is__init__Passed to num of
test.print_num()
Execution result
The number passed as an argument is 10.
Contrary to the constructor, the method that is called when an instance is no longer needed and is deleted is called a destructor. The destructor is defined by a method named "del".
class Test:
def __init__(self):
print('The constructor was called')
def __del__(self):
print('Destructor was called')
test = Test() #Create an instance
del test #Delete instance
Execution result
The constructor was called Destructor was called
Python classes can also extend and extend from other classes. When inheriting a class, specify the parent class in the class statement. Use super () to call the methods of the parent class.
class Test:
def __init__(self, num):
self.num = num;
def print_num(self):
print('The number passed as an argument is{}is.'.format(self.num))
class Test2(Test): #Inherit the Test class
def print_test2_info(self):
print('This class inherits from the Test class.')
super().print_num() #Parent class print_num()Call
test = Test2(10)
test.print_test2_info()
Execution result
This class inherits from the Test class. The number passed as an argument is 10.
Recommended Posts