[Python for Hikari] Chapter 09-02 Classes (Creating and instantiating classes)

[Python] Chapter 09-02 Creating and instantiating classes

In the previous section, we explained what an object is, and explained that numbers, lists, etc. are all objects. For example, numeric objects and list objects.

This time I would like to touch on how to create an object yourself.

What is an object blueprint?

I explained that there are numeric, list, and string type objects in Python. For example, if it is a character string type object, there are actions (methods) such as "capitalize only the beginning of the data" and "find the specified character in the data".

This is a string type object, but in fact there is a ** blueprint ** for this string type object in Python. (I'm not usually aware of it) This blueprint is called ** class **.

Until now, I have used numbers, strings, lists, etc. unknowingly, but every time I use them, I create an object based on the blueprint (class). ** **

In this blueprint, for example, ** what to do with data (also called attributes or properties) **, ** how to handle methods **, etc. are written.

The following is an object design diagram called a class diagram (*) </ font>, which is often used when designing programming.

For example, the following class diagram example is a blueprint representing a person.

image.png

The (*) </ font> class diagram is one of the basic diagrams of UML (Unified Modeling Language), and it often expresses the relationships between the classes that make up the system. Indicates the attributes and methods that the class holds.

Creating a class

Now, I would like to finally create a class and create an original object. First, in general, write as follows.

class class name:
Constructors and methods that define classes

There are some terms I haven't heard about, but I'll explain them later, but under the: (colon), I'll describe the contents of the class diagram.

However, it is difficult to do general things suddenly, so here I will explain using an example of a class definition that represents a bird. Let's create a Bird type object program on the assumption that it has the following data (attributes) and methods. 【attribute】 ・ Name ・ Color

** [Method] ** ・ Flying method -Method to print bird status (print_status)

First, let's show this in a class diagram. image.png

First, let's create it from a Bird type class. Write the following code in samp09_02_01.py </ font>. * </ font> From this time, we will name it with _ (underscore) of ** samp09_02_01.py ** instead of samp09-02-01.py.

.samp09_02_01.py


class Bird:
    def __init__(self, name, color):
        print('-----Call the constructor as soon as you instantiate it.-----')
        self.name = name
        self.color = color

    #Method to fly
    def flying(self, m):
        print('-----Call the flying method.-----')
        print(f'With rustling{self.name}Fly in the sky.')
        print(f'{m}Flying at a height of m.')

    #Method to output the status of instantiated Bird
    def print_status(self):
        print('-----print_Call the status method.-----')
        print(f'{self.color}It is a colored bird.')

Now, let's execute this program "flying method (flying)" and "status display method (print_status)" together with the class diagram. But you can see that nothing is displayed.

To solve this, you need ** instantiation **.

Instantiation

Right now, the execution result was not displayed in the above program, but in the above program, I just made a blueprint of the Bird class, that is, ** Bird type **. At this stage, we have only defined the type "Bird is like this", and there is no concrete bird entity. (As an example, the type of Taiyaki is defined, but Taiyaki itself is not done)

It needs to be materialized from this blueprint, which is called ** instantiation **. Further materialized ones are called ** instances **.

You need to add the following code to instantiate it. Add the following code to samp09_02_01.py </ font>.

.samp09_02_01.py


class Bird:
    def __init__(self, name, color):
        print('-----Call the constructor as soon as you instantiate it.-----')
        self.name = name
        self.color = color

    #Method to fly
    def flying(self, m):
        print('-----Call the flying method.-----')
        print(f'With rustling{self.name}Fly in the sky.')
        print(f'{m}Flying at a height of m.')

    #Method to output the status of instantiated Bird
    def print_status(self):
        print('-----print_Call the status method.-----')
        print(f'{self.color}It is a colored bird.')


#Specify the bird name and color when instantiating and assign it to a variable called chi
chi = Bird('Chitti', 'tea')

By doing this, you will have an instance of a bird (Bird), which is shown in the figure below. image.png

Bird with a variable called ** chi ** (previously described as a tag).

constructor

As mentioned in the comments in the program, the place ** def \ _ \ _ init \ __ (self, name, color): ** is called the ** constructor **.

In fact, without this constructor, the data (attributes) ** name ** (this time "chitch") and ** color ** (this time "brown") will not be reflected when instantiated.

Therefore, in order to reflect the data (attribute) at the same time by instantiating, the value is reflected in ** name ** and ** color ** respectively in the constructor.

I'm curious about this ** self **, but in fact it indicates the ** instance itself ** and may be the ** first argument **. (It doesn't have to be called self, but it's often customary to call it self.) So, in the constructor, "self.name = name" means that ** "name of the instance itself" ** is replaced with ** "name (actually contains the value" chitchi ")" **. I'm doing it.

By doing so, it is possible to give the instantiated bird (Bird) the following attributes. * </ font> Confirm that the color is "brown" and the name is "chitch".

image.png

Operate what you have instantiated

So far, you have created an object by creating a Bird type class and instantiating it. As I mentioned in the previous section, I explained that ** objects have data (attributes) and methods **. How about this time? Bird type objects have attributes ** name ** and ** color **, and methods ** flying () ** and ** print_status () **.

Let's actually operate them. Please add to the previous program. (Addition is near the end)

.samp09_02_01.py


class Bird:
    def __init__(self, name, color):
        print('-----Call the constructor as soon as you instantiate it.-----')
        self.name = name
        self.color = color

    #Method to fly
    def flying(self, m):
        print('-----Call the flying method.-----')
        print(f'With rustling{self.name}Fly in the sky.')
        print(f'{m}Flying at a height of m.')

    #Method to output the status of instantiated Bird
    def print_status(self):
        print('-----print_Call the status method.-----')
        print(f'{self.color}It is a colored bird.')


#Specify the bird name and color when instantiating and assign it to a variable called chi
chi = Bird('Chitti', 'tea')

#Call the flying method of a Bird type object
chi.flying(15)

#Bird type object print_Call the status method
chi.print_status()

[Execution result] </ font> ----- Call the constructor as soon as you instantiate it. ----- ----- Call the flying method. ----- Bass Bass and Chitchi fly in the sky. It is flying at a height of 15m. ----- Call the print_status method. ----- It is a brown bird.

First, go through the processing of the class (Bird),

chi = Bird('Chitti', 'tea')

Instantiated by. This will create a Bird type object with the value chi. At the same time by the constructor ** "----- Call the constructor as soon as it is instantiated. -----" ** Is output, and then the values of ** name ** and ** color ** are assigned.

next,

chi.flying(15)
chi.print_status()

Calls the behavior of a Bird type object called chi.

However, it is difficult to do so, so let's think about it as follows. Let's compare the list type object with the Bird type object created this time.

List type object Bird type object
Instance creation ls = [10, 15, 20] chi = Bird('Chitti', 'tea')
Attributes (data) at this time 10, 15, 20 'Chitti', 'tea'
In the object
Some method execution 1
ls.count(10)
(A method to find out how many numbers 10 are)
chi.flying(15)
(A method that outputs a flying command and also outputs the height)
In the object
Execution of some method 2
ls.clear()
(Method to delete elements in list)
chi.print_status()
(Method to output status)

Examine the type

In the above example, we explained that ** chi ** is an object of type ** Bird **, but you can also find out if it really is. This time, let's enter the following code from ** Python Console **.

>>> from chap09.samp09_02_01 import Bird
>>> chi = Bird('Chitti', 'tea')
-----Call the constructor as soon as you instantiate it.-----
>>> type(chi)
<class 'chap09.samp09_02_01.Bird'>

Indeed, it turned out to be a Bird type object. (It may change depending on the saved folder and program name, but it is still a Bird object.)

Finally

I explained how to instantiate from a blueprint called a class. I didn't explain this time, but it is possible to create multiple instances (≒ objects) from one blueprint.

This time, I assigned the instantiated variable to the variable ** chi **, but let's actually change the variable and create multiple birds with different names and colors.

For objects, it can be difficult, but we are still using the methods and functions we have used so far. It will be easier to understand if you compare it with the table above.

Return to [Table of Contents Link]

Recommended Posts