An introduction to object-oriented programming for beginners by beginners

Overview

The purpose of this article is to make it as easy as possible for people (including myself) who are allergic to object-oriented programming, "I'm not afraid of object-oriented programming."

Since I am a beginner in programming, please understand that the explanation of terms may be different or some expressions may be difficult to understand.

Who is the target of this article

  1. I want to know roughly about object-oriented programming
  2. I want to know what kind of content the article written by a beginner is
  3. I want to read the source code written by others
  4. Other readers other than 1-3

What is object-oriented programming in the first place?

According to Wikipedia

[Object Oriented Programming-Wikipedia](https://ja.wikipedia.org/wiki/%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF % E3% 83% 88% E6% 8C% 87% E5% 90% 91% E3% 83% 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3 % 83% B3% E3% 82% B0)

What is object-oriented programming?

Object-oriented programming (object-oriented programming, English: object-oriented programming, abbreviation: OOP) is to combine data and methods that are closely related to each other into an object, which has different properties and roles. It is a software development method that builds the entire program through various definitions of objects and the settings of various processes that interact with these objects.

What is object-oriented?

The term object-oriented itself was coined by computer scientist Alan Kay. Kay, who was impressed by the design of the language "Simula" released in 1962, said this coined word for the first time in explaining the language design of "Smalltalk", which he started publishing in 1972. It was sent to the world. It should be noted that the object-oriented programming centered on message passing, which Kay showed, is not widely recognized, and only focuses on the program concept of objects. At the same time, object-oriented programming away from Kay's hands shifted to an interpretation centered on abstract data types, and with the opportunity of "C ++" released by computer scientist Bjarne Stroustrup in 1983, Japan The paradigms of encapsulation, inheritance, and polymorphism, which are generally called the three major elements of OOP, have been established.

So what is it?

A collection of data and methods that are closely related to each other.

Object Oriented Programming (OOP)

--The source code is written in Python 3.9. ――I am writing the source code using a car as an example.

Classes and instances

What is a class

It corresponds to the blueprint when making a car.

Below is the sample code.

sample.py


class Car:
    def __init__(self):
        pass

What is an instance?

It corresponds to the car itself (entity) that was made.

Below is the sample code.

sample.py


class Car:
    def __init__(self):
        pass

car = Car()  #instance

What kind of information, what parts, and what functions does a car have?

For example, vehicle type, number, color, engine, tires, etc ... And there are also accelerators and brakes.

Let's add (some of) this information to the blueprint.

Below is the sample code.

sample.py



class Car:
    def __init__(self, name, color):
        self.name = name  #Car name
        self.color = color  #Car color

    def start_engine(self):
        print("I started the engine.")

    def stop_engine(self):
        print("I turned off the engine.")

    def accelerator(self):
        print("I stepped on the accelerator.")

    def brake(self):
        print("I stepped on the brake.")

mycar = Car("Prius", "White")  #Instance generation
mycar.start_engine()  #I started the engine. Is displayed
mycar.accelerator()  #I stepped on the accelerator. Is displayed
mycar.brake()  #I stepped on the brake. Is displayed
mycar.stop_engine()  #I turned off the engine. Is displayed

Let's leave this for the time being.

Three major elements of OOP (Object Oriented Programming)

Earlier, I mentioned a little in the Wikipedia quote.

  1. Encapsulation
  2. Inheritance
  3. Diversity

Encapsulation

Encapsulation-Wikipedia

Encapsulation in programming (encapsulation or English: encapsulation) means to combine data (attributes) and methods (procedures) into one object and hide its contents. The concept of encapsulation can be seen as one of the constructs of information hiding in D.L. Parnas.

Objects in object-oriented programming are created by encapsulating information by classes.

Encapsulation hides information that you do not want to disclose to the outside.

In Python, encapsulation is done by prefixing the variable name (or function name) with an underscore. However, in Python it is best not to encapsulate as much as possible. If there is one underscore, it should be used only within that class, In the case of two underscores (called dander), the use is more restricted. It's a bit special to call, but it doesn't mean you can't.

It may also be used to easily disguise complex processing. In that case, you should actively use it. If you compare it with a car, various children are done inside to start the engine, It's like the driver doesn't have to know it.

Below is the sample code.

sample.py



class Car:
    def __init__(self, name, color):
        self.name = name  #Car name
        self.color = color  #Car color
        self._age = "2020 model year"  #Model year
        self.__engine = "gasoline engine"  #Engine type


mycar = Car("Prius", "White")
print(mycar._age)  #Executable,Displayed as "2020 model year"
mycar._age = "2019 model year"  #Substitution is also possible * Should not be

print(mycar.__engine)  #This will cause an error
# AttributeError: 'Car' object has no attribute '__engine'
print(mycar._Car__engine)  #Executable,It says "gasoline engine" but shouldn't

Inheritance

[Inheritance (programming)-Wikipedia](https://ja.wikipedia.org/wiki/%E7%B6%99%E6%89%BF_(%E3%83%97%E3%83%AD%E3%82) % B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3% E3% 82% B0))

Inheritance (inheritance) is one of the concepts that make up object orientation. When one object inherits the characteristics of another object, it is said that there is an "inheritance relationship" between the two. (Omitted) In general, when B inherits A, the semantic relationship (Is-a relationship) of "B is a A." (B is a type of A) holds. Therefore, it is often not appropriate to have an inheritance relationship between semantically unrelated classes just because they have the same behavior.

There is "delegation" in a concept similar to inheritance, but in inheritance, the inheritance relationship once determined is usually not changed, but the subject of delegation can be changed as needed.

There are aggregation and composition as concepts that are different in hierarchy from inheritance with Is-a relationship, but this is an inclusion relationship in which the relationship between classes is Has-a, and it is between classes. Relationships are sparser than inheritance.

In summary, it is better to use inheritance if the is-a relationship holds. However, it is better to refrain from using inheritance unnecessarily.

If you compare it with a car Sports car is a car Special vehicle is a A car, etc.

Below is the sample code.

The Car class is the same as before.

sample.py


class Car:
    def __init__(self, name, color):
        ...
    ...


class SportCar(Car):
    def __init__(self, name, color):
        super().__init__(name, color)


class SpecialCar(Car):
    def __init__(self, name, color):
        super().__init__(name, color)

The inherited class is called the parent class, and the inherited class is called the child class. In the sample code above, the Car class is the parent class and the SportCar and SpecialCar are the child classes. The child class super () .__ init__ (name, color) calls the parent class __init__.

Diversity (polymorphism)

[Polymorphism-Wikipedia](https://ja.wikipedia.org/wiki/%E3%83%9D%E3%83%AA%E3%83%A2%E3%83%BC%E3%83%95%E3 % 82% A3% E3% 82% BA% E3% 83% A0)

Polymorphism describes the nature of the type system of a programming language, and that each element of the programming language (constants, variables, expressions, objects, functions, methods, etc.) belongs to multiple types. Refers to the property of forgiving.

If you look at Wikipedia, you probably don't understand what you're saying, so take a look at the sample code.

Below is the sample code.

sample.py



class Car:
    def __init__(self, name, color):
        ...

    def accelerator(self):
        print(f"I stepped on the accelerator.({self.name})")

    def brake(self):
        print(f"I stepped on the brake.({self.name})")


class SportCar(Car):
    ...


class SpecialCar(Car):
    ...


cars = [Car("Prius", "White"), SportCar("Ferrari", "Red"), SpecialCar("ambulance", "White")]
for car in cars:
    car.accelerator()
    car.brake()

Execution result.


I stepped on the accelerator.(Prius)
I stepped on the brake.(Prius)
I stepped on the accelerator.(Ferrari)
I stepped on the brake.(Ferrari)
I stepped on the accelerator.(ambulance)
I stepped on the brake.(ambulance)

By preparing a method with the same name, it is possible to use it without being aware of the type (class).

The whole explanation is over

That's all for the explanation.

From now on, I will modify the source code to a program that seems to be object-oriented programming.

Click here for the original source code

sample.py


class Car:
    def __init__(self, name, color):
        self.name = name  #Car name
        self.color = color  #Car color

    def start_engine(self):
        print("I started the engine.")

    def stop_engine(self):
        print("I turned off the engine.")

    def accelerator(self):
        print("I stepped on the accelerator.")

    def brake(self):
        print("I stepped on the brake.")


class SportCar(Car):
    def __init__(self, name, color):
        super().__init__(name, color)


class SpecialCar(Car):
    def __init__(self, name, color):
        super().__init__(name, color)


cars = [Car("Prius", "White"), SportCar("Ferrari", "Red"), SpecialCar("ambulance", "White")]
for car in cars:
    car.accelerator()
    car.brake()

I'll fix it a little. The car does not have the functions of start engine and stop engine. There is only one engine button. So ... Combine start_engin (self) and stop_engine (self) into one. Also, make sure that the engine is running and the engine is running.

sample.py


class Car:
    def __init__(self, name, color):
        self.name = name  #Car name
        self.color = color  #Car color
        self._engine = False  #True when the engine is running,False when not on

    def engine(self):
        print(f"[{self.name}]", end=" ")
        self._engine = not(self._engine)
        if self._engine:
            print("I started the engine.")
        else:
            print("I turned off the engine.")

    def accelerator(self):
        print(f"[{self.name}]", end=" ")
        print("I stepped on the accelerator.")

    def brake(self):
        print(f"[{self.name}]", end=" ")
        print("I stepped on the brake.")


class SportCar(Car):
    def __init__(self, name, color):
        super().__init__(name, color)


class SpecialCar(Car):
    def __init__(self, name, color):
        super().__init__(name, color)


cars = [Car("Prius", "White"), SportCar("Ferrari", "Red"), SpecialCar("ambulance", "White")]
for car in cars:
    car.engine()
    car.accelerator()
    car.brake()
    car.engine()

Execution result.


[Prius]I started the engine.
[Prius]I stepped on the accelerator.
[Prius]I stepped on the brake.
[Prius]I turned off the engine.
[Ferrari]I started the engine.
[Ferrari]I stepped on the accelerator.
[Ferrari]I stepped on the brake.
[Ferrari]I turned off the engine.
[ambulance]I started the engine.
[ambulance]I stepped on the accelerator.
[ambulance]I stepped on the brake.
[ambulance]I turned off the engine.

Is it like this?

I couldn't think of a good example, so it may have been difficult to understand. I think that object-oriented programming will be more useful as the number of people increases.

This time it ends.

Until the end Thank you for reading. If you have any mistakes or advice, I would appreciate it if you could comment.

Recommended Posts

An introduction to object-oriented programming for beginners by beginners
Introduction to Programming (Python) TA Tendency for beginners
An introduction to Python Programming
An introduction to Mercurial for non-engineers
An introduction to Python for non-engineers
An introduction to OpenCV for machine learning
Beginners read "Introduction to TensorFlow 2.0 for Experts"
An introduction to Python for machine learning
An introduction to Python for C programmers
An introduction to machine learning for bot developers
For beginners to build an Anaconda environment. (Memo)
An introduction to statistical modeling for data analysis
An introduction to voice analysis for music apps
[For beginners] How to study programming Private memo
[For beginners] Introduction to vectorization in machine learning
Introduction to Deep Learning (1) --Chainer is explained in an easy-to-understand manner for beginners-
AOJ Introduction to Programming Topic # 1, Topic # 2, Topic # 3, Topic # 4
An introduction to private TensorFlow
An introduction to machine learning
AOJ Introduction to Programming Topic # 7, Topic # 8
AOJ Introduction to Programming Topic # 5, Topic # 6
An introduction to Bayesian optimization
~ Tips for beginners to Python ③ ~
Introduction to Python For, While
■ Kaggle Practice for Beginners --Introduction of Python --by Google Colaboratory
[Explanation for beginners] Introduction to convolution processing (explained in TensorFlow)
[Explanation for beginners] Introduction to pooling processing (explained in TensorFlow)
An introduction to functional programming to improve debugging efficiency in 1 minute
[Python] Introduction to graph creation using coronavirus data [For beginners]
[Introduction to Python3 Day 1] Programming and Python
Introduction to Generalized Estimates by statsmodels
[Python Tutorial] An Easy Introduction to Python
Python learning memo for machine learning by Chainer Chapter 8 Introduction to Numpy
How to solve dynamic programming algorithm problems (as seen by beginners)
Python learning memo for machine learning by Chainer Chapter 10 Introduction to Cupy
Python learning memo for machine learning by Chainer Chapter 9 Introduction to scikit-learn
[2020 version for beginners] Recommended study method for those who want to become an AI engineer by themselves
Answer to AtCoder Beginners Selection by Python3
Programming environment for beginners made on Windows
[For beginners] Super introduction to neural networks that even cats can understand
Django tutorial summary for beginners by beginners ③ (View)
Decide who to vote for by lottery
Recurrent Neural Networks: An Introduction to RNN
Introduction to discord.py (1st day) -Preparation for discord.py-
Introduction to AOJ Programming (ALDS1)-# 7 Tree Structure
An introduction to self-made Python web applications for a sluggish third-year web engineer
Django tutorial summary for beginners by beginners ⑤ (test)
Assigned to a laboratory by integer programming
An Introduction to Object-Oriented-Give an object a child.
Introduction to Graph Database Neo4j in Python for Beginners (for Mac OS X)
A textbook for beginners made by Python beginners
Memo # 4 for Python beginners to read "Detailed Python Grammar"
[What is an algorithm? Introduction to Search Algorithm] ~ Python ~
The fastest way for beginners to master Python
Django tutorial summary for beginners by beginners ⑦ (Customize Admin)
Django tutorial summary for beginners by beginners ⑥ (static file)
How to make Spigot plugin (for Java beginners)
Python for super beginners Python for super beginners # Easy to get angry
I tried to get an image by scraping
An introduction to Cython that doesn't go deep
Inspired by an article for newcomers (abbreviated below)