Python basic operation 3rd: Object-oriented and class

#Python basic operations

Introduction

Review the basic operations of Python only for the parts that you are uneasy about. As the third step, we describe object orientation and classes.

What is object orientation?

In short, it handles data and operations as a group. It's like putting variables and functions together. The group is called ** object **.

In object orientation The processing target is divided into object units, and messages are exchanged with each other to proceed with processing.

Object-oriented benefits

Places where maintainability can be expected, such as minimizing the impact of corrections

Encapsulation

In object-oriented programming, there is a mechanism that allows the data inside an object to be accessed only by using a prepared operation, which is called encapsulation. The image is shown below.

図1.png

In Fig. 1, the processing represents the processing from outside the object, and each blue frame represents the object. It can be seen that there are data and operation elements inside the object, and the data cannot be accessed directly from the outside. However, you can access the data by stepping on the operation.

Arrangement of words

Object: A collection of data and operations Class: Something like an object blueprint Instance: A materialized object

In the following, we will check with the actual code.

Code 1

class.py


"""
2020/12/14
@ Yuya Shimizu

class
"""
#Definition of a class called User
class User:
    #constructor
    def __init__(self, name, password):
        self.name = name
        self.password = password

    #Login method
    def login(self, password):
        if self.password == password:
            return True
        else:
            return False

    #success method
    def success(self):
        print('User: ' + self.name + ' --- login successfully !!')
        
    #failure method
    def failure(self):
        print('User: ' + self.name + ' --- sorry, password is not correct')

#Instantiate to a
a = User('Yuya', 'PassWord')

user_input = input('\nplease input your password\n>>')
if a.login(user_input):
    a.success()
else:
    a.failure()

class~Design an object with Object name() Instantiate with By specifying the operation for the instance, the object is accessed.

Code 2

class.py


"""
2020/12/14
@ Yuya Shimizu

class
"""
#Definition of a class called User
class User:
    #constructor
    def __init__(self, name, password):
        self.name = name
        self.password = password

    #Login method
    def login(self, password):
        if self.password == password:
            return True
        else:
            return False

    #success method
    def success(self):
        print('User: ' + self.name + ' --- login successfully !!')
        
    #failure method
    def failure(self):
        print('User: ' + self.name + ' --- sorry, password is not correct')

#Instantiate to a
a = User('Yuya', 'PassWord')

user_input = input('\nplease input your password\n>>')
if a.login(user_input):
    a.success()
else:
    a.failure()

#Class inheritance
class GuestUser(User):
    def __init__(self):
        super().__init__('guest', 'guest')

guest = GuestUser()
user_input = input('\nGuest, please input your password\n>>')
if guest.login(user_input):
    guest.success()
else:
    guest.failure()

There is something called inheritance in class. A parent class is defined, and the same structure as the parent class can be inherited by the child class. Only the inherited part is shown below.

#Class inheritance
class GuestUser(User):
    def __init__(self):
        super().__init__('guest', 'guest')

There is a parent class as an argument after the object name, and it is also possible to change the argument in the class __init __ ()` ``. It is executed by super () .__ init __ ()` ``.

Does Python have access attributes like public or private?

Not from the conclusion. However, instead, there is a rule that variables and methods starting with __`` and` `__ are not referenced from the outside, and an error occurs when accessing them. Actually verify.

Verification

rule_.py


"""
2020/12/14
@ Yuya Shimizu

class
Underscore rules
"""
#Definition of a class called User
class User:
    #constructor
    def __init__(self, name, password):
        self.name = name
        self.password = password
        self.__password = password
        

#Instantiate to a
a = User('Yuya', 'PassWord')

print(a.name)
print(a.password)
print(a.__password)

inspection result

The execution result is shown below.

Yuya
PassWord
Traceback (most recent call last):
  File "D:/Python Skills/Basic/Object-oriented and class/rules__.py", line 25, in <module>
    print(a.__password)
AttributeError: 'User' object has no attribute '__password'

From the execution result, it can be seen that an error has occurred only in the part of ``` print (a.__ password) , and it cannot be accessed just by adding __ .

Impressions

I've used the class several times, but I finally understood how it works and was convinced. I didn't seem to know the rules of underscores, so I'm glad I could understand them here.

References

Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha

Recommended Posts

Python basic operation 3rd: Object-oriented and class
[python] class basic methods
Basic operation of Python Pandas Series and Dataframe (1)
Python: Class and instance variables
Python installation and basic grammar
Python class variables and instance variables
Installing Python 3 on Mac and checking basic operation Part 1
Python (Python 3.7.7) installation and basic grammar
Java and Python basic grammar comparison
perl objects and python class part 2.
Python class definitions and instance handling
[python] week1-3: Number type and operation
Python Basic Course (14 Modules and Packages)
perl objects and python class part 1.
Basic Python operation 2nd: Function (argument)
Python basic operation 1st: List comprehension notation
Elasticsearch installation and basic operation for ubuntu
[Python] Difference between class method and static method
Python data structure and operation (Python learning memo ③)
Differences between Ruby and Python (basic syntax)
Talking about Python class attributes and metaclasses
[Python] class, instance
RF Python Basic_01
Correspondence summary of array operation of ruby and python
What is "functional programming" and "object-oriented" in Python?
[python] vector operation
About python, class
Python3 Engineer Certification Basic Exam-Notes and Problem Trends-
[python] Difference between variables and self. Variables in class
Basic operation list of Python3 list, tuple, dictionary, set
I wrote a class in Python3 and Java
Basic Python writing
Python OS operation
Trouble with Python pseudo-private variables and class inheritance
[Python / Chrome] Basic settings and operations for scraping
Python3 basic grammar
[Python] Matrix operation
Python class, instance
RF Python Basic_02
[Python] Class type and usage of datetime module
#Python basics (class)
[Python] Convert general-purpose container and class to each other
Web system construction (super basic) ③: DB server construction and basic operation
Sample of getting module name and class name in Python
Web system construction (super basic) ②: AP server construction and basic operation
[python] Compress and decompress
About Class and Instance
[Python] Operation of enumerate
Python basic course (12 functions)
Python I'm also basic
Python class (Python learning memo ⑦)
Python basic grammar / algorithm
Python and numpy tips
Python Basic Course (7 Dictionary)
[Python] pip and wheel
"Object-oriented" learning with python
Python basic course (2 Python installation)
case class in python
Basic sorting in Python
Batch design and python
Python iterators and generators