Python basic course (13 classes)

Object Oriented and [Object Oriented Programming](http://e-words.jp/w/E382AAE38396E382B8E382A7E382AFE38388E68C87E59091E382AFE38388E68C87E59091E38397E It's an essential concept. All data in a Python program is represented as objects or relationships between objects. All the strings and lists that have been described so far are objects.

However, this page does not provide a "plain" and "accurate" explanation of object orientation. Therefore, even in the explanation of strings and lists, I have not dared to explain the part about objects (and methods). The rest of this article will explain how to use classes and objects in Python, assuming you understand object orientation.

class

The program that actually uses the class and the object is written below. Please execute it and check the operation.

class_explain.py


class Spam:
	val = 100
	def ham(self):
		self.egg('call method')

	def egg(self,msg):
		print("{0}".format(msg))
		print(("{0}".format(self.val)))

spam = Spam()
spam.ham()

The result is as follows.

call method 100

In Python, classes are created with ** class ** * class name ***: **. The class name starts with an uppercase letter. Class variables and in-class functions (= methods) are defined using indentation. Objects are created with * object * ** = ** * class () *. The method is called with * object.method () *. If you explain the above program in Japanese

  1. Create an object spam of class Spam
  2. The spam object calls the ham method
  3. The ham method of the spam object calls the egg method of the spam object (= itself)
  4. The spam object's egg method outputs the argument msg
  5. The egg method outputs the variable val of the spam object

The point is the first argument ** self ** of the method. For those who entered Python from other languages You might wonder, "What is this self when spam.ham () has no arguments?" In Python, methods have at least one argument. It is customary to always name this first argument self. By using self, you can get the variable of the object itself or call the method. It is "this" in Java.

constructor

A special function that is called when an object is created is called a constructor. Initialization of the data handled by the object is performed here. The constructor is defined with the name __init __ (). There are two " _ "before and after. be careful.

constructor_explain.py


class Spam:
    def __init__(self,ham,egg):
        self.ham = ham
        self.egg = egg
    def output(self):
        sum = self.ham + self.egg
        print("{0}".format(sum))

spam = Spam(5,10)
spam.output()

The result is as follows.

15

Destructor

The opposite of the constructor, this function is automatically executed when the object is no longer needed and Python deletes it. Define it with a method named __del__. But in most cases you don't define a destructor. As a reason

We use with to free resources, but we won't explain it here because it goes beyond the level.

Inheritance

"Inheritance" is defining one class as a class with data and methods from another class. Inheritance is an important idea common to object-oriented programming languages as well as Python. Please execute the following program.

extend_explain.py


class Base:
    basevalue = "base"
    def spam(self):
        print("Base.spam()")

    def ham(self):
        print("ham")

class Derived(Base):
    def spam(self):
        print ("Derived.spam()")
        self.ham()

derived = Derived()
print("{0}".format(derived.basevalue))
derived.ham()

** class ** * class name (base class name) * **: ** allows you to define a class (derived class) that inherits the variables and methods of the base class. The derived class inherits the variables and methods of the base class, so the output looks like this:

base ham

Multiple inheritance

Python allows "multiple inheritance" to inherit multiple base classes. ** class ** * Class name (base class name 1, base class name 2, ...) *

multi_extend.py


class A:
	def method(self):
		print("class A")

class B:
	def method(self):
		print("class B")

class C(A):
	def method(self):
		print("class C")

class D(B,C):
	pass

d = D()
d.method()

The output result will be ** class B **. Although rarely used, you can create a class that does nothing by writing pass in the class. When you call the method method () of the object d of class D, you can use the base classes B and C of class D. The class B method method () described earlier is called and ** class B ** is output. If class B of the above program is described only by pass like class D, the method method () does not exist in the base class B. The class C method method () is called and the output is ** class C **. If only pass is described in class C, the method method () of class A, which is the base class of class C, will be called. ** class A ** is output. If class A is described only as pass, an exception will be thrown because method () does not exist in any class.

Creating complex multiple inheritance can result in an error because the method search order cannot be determined. be careful.

private and public

Encapsulation is an important element in object-oriented programming. In Python, you can make a variable or method private by prepending "\ _ \ _" (two _). Please execute the following program.

private_explain.py


class Spam:
    __attr = 100
    def __init__(self):
        self.__attr = 999
    def method(self):
        self.__method()
    def __method(self):
        print(self.__attr)

spam =Spam()
spam.method()   #OK
spam.__method() #NG
spam.__attr     #NG

The spam.method () line runs fine, but the spam. \ _ \ _ Method () line gives an error. The method method of class Spam is public because it doesn't start with "\ _ \ _". It can be called directly from the object. I'm calling \ _ \ _method () with "\ _ \ _" at the beginning in the method method, Since it is a reference from the inside, no error will occur. But if the spam object tries to call \ _ \ _method () directly, \ _ \ _ Method () with "\ _ \ _" at the beginning cannot be called because it is private, and an error will occur. This also applies to spam. \ _ \ _ Attr.

Next: Python Basic Course (14 Modules and Packages)

Recommended Posts

Python basic course (13 classes)
Python Basic Course (7 Dictionary)
Python basic course (9 iterations)
Python Basic Course (11 exceptions)
Python basic course (6 sets)
Python Basic Course (Introduction)
Python basic course (8 branches)
Python Basic Course (3 Python Execution)
Python Basic Course (5 List Tuples)
Python Basic Course (1 What is Python)
Python Basic Course (14 Modules and Packages)
RF Python Basic_01
Basic Python writing
Python3 basic grammar
RF Python Basic_02
Python Basic Course (at the end of 15)
Python basic course (4 numeric type / character string type)
Python I'm also basic
Python basic grammar / algorithm
Basic sorting in Python
[python] class basic methods
Python3 cheat sheet (basic)
Python basic grammar (miscellaneous)
Python basic memorandum part 2
Python basic memo --Part 2
Basic Python command memo
Python basic grammar note (4)
Python basic grammar note (3)
Basic knowledge of Python
Python basic grammar memo
OpenCV basic code (python)
Python basic memo --Part 1
python memorandum super basic
Python basic if statement
Python Basic --Pandas, Numpy-
Python application: Pandas Part 1: Basic
About python objects and classes
BASIC authentication with Python bottle
Python basic dict sort order
[Python] Using OpenCV with Python (Basic)
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Python classes learned in chemoinformatics
Paiza Python Primer 8: Understanding Classes
Python basic grammar (miscellaneous) Memo (2)
Basic Python grammar for beginners
[Python] [SQLite3] Operate SQLite with Python (Basic)
Basic usage of Python f-string
I learned Python basic grammar
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
Java and Python basic grammar comparison
That Python code has no classes ...
Python ABC-Abstract Classes and Duck Typing
Python
Scraping with Selenium in Python (Basic)
Python: A Note About Classes 1 "Abstract"
Python course for data science_useful techniques
What was surprising about Python classes
[Python] About Executor and Future classes
I took Progete's Python Learning Course I