Skip to content

[Python] Tutorial(15) Class

The class of Python is the basically type of module designing. It is also the object-oriented of Python.

We can give the object a function to copy some properties if we need.

It is quite convenient to apply the “Class” to the object. For example, today we want to make a ” The Sims ” game (I don’t know if you have played hahaha), each character has his own. “Panel Properties”.
So, do we have to re-establish the character of the character every time we create a character?

Of course not! We can set the Class that has the character panel number, and assign the character to the “human” Class each time you need to create a character.

Maybe you will say that we can also use function to complete it?
For example, save the character data as a Json file (maybe I will mention the JSON access method in Python in the following chapters), each character has its own different properties.

of course! I think this is also a way to do that.

However, Class has a more convenient point than using function to create properties: inherit Class, or extend the class we build.

Suppose we are going to have a piece of information today (in this case, we can also use the example of ” The Sims “), and the characters have added police, firefighters, etc. Then, we are likely to need to add the attributes of the characters! For example, the level of a new occupation or exclusive skills.

Then, we can create a new category that belongs to the DLC, inherit the original “human” category, and update the new occupation on top of it.

Maybe you will still say: However, modifying the function we created and adding the character data to the Json file seems to have the same effect?

Don’t worry, I haven’t finished it yet!

If there is a new profession opposite the police: “The underworld”, then we may need to extend the categories to include some attributes that are specific to these NPCs that can interact with the protagonist.

Then, we can still inherit the “human” class and re-establish the Class that belongs to the NPC.

And function, it is very likely to have to write a different function to distinguish the attributes of the characters we manipulate, as well as the properties of other NPCs.

Of course, I admit that function can actually achieve the same function, but it may be somewhat unintuitive in the category.

In fact, I think that we really need to learn the class to experience from actual combat. I learned the class, which I think is an important point in learning Python.

Below, let’s start with the last note of our basic Python tutorial!


Class

We really made Class in the category of “human” this time.

class Human():
    def __init__(self, name, age):
        self.name = name
        self.age = age


if __name__ == '__main__':
    clay = Human('Clay', 25)
    print('Name:', clay.name)
    print('Age:', clay.age)


Output:

Name: Clay
Age: 25

The “class” directive follows the name of the class we want to create. Here I set up the Human category.

__init__ is the initialized block. Whenever this class is created as an object, the code below is executed. It can be seen that when I first created this category of objects, I entered the attributes of “Human” – “name” and “age”.

I can see that I built the clay as a human object. Clay This object is called Clay and is 25 years old.

It is worth noting that if the attribute under the class is not intended to be externally visible, you can put a symbol such as “__” in front of the attribute.

Example:

class Human():
    def __init__(self, name, age):
        self.name = name
        self.__age = age


if __name__ == '__main__':
    clay = Human('Clay', 25)
    print('Name:', clay.name)
    print('Age:', clay.__age)


Output:

AttributeError: 'Human' object has no attribute '__age'
Name: Clay

We can see that the name attribute is printed as well, but __age is relatively incorrect. The program shows that there is no such property under Human.

In this way, we can create properties that are not visible to the outside, only for internal use. I think this can reduce the possibility that we give the object property an error.

Of course, we can also show these “hidden” attributes.

class Human():
    def __init__(self, name, age):
        self.name = name
        self.__age = age

    def who(self):
        return self.name

    def how_old(self):
        return self.__age


if __name__ == '__main__':
    clay = Human('Clay', 25)
    print('Name:', clay.who())
    print('Age:', clay.how_old())


Output:

Name: Clay
Age: 25

Hey! We have successfully printed the hidden attributes inside this time! It’s just that we take a long way, define function inside the class, and then pass back the value of the internal property!


Inherit

And then, let’s talk about how to make a newly created class inherit the class that existed before.

We set up a class called Police as a new profession, and of course, he has the ability to write for Human.

class Human():
    def __init__(self, name, age):
        self.name = name
        self.__age = age

    def who(self):
        return self.name

    def how_old(self):
        return self.__age


class Police(Human):
    def __init__(self, name, age, power):
        super().__init__(name, age)
        self.power = power

    def PK(self):
        if self.power > 50:
            return True
        else:
            return False


if __name__ == '__main__':
    clay = Police('Clay', 25, 70)
    print('Name:', clay.who())
    print('Age:', clay.how_old())
    print('PK:', clay.PK())


Output:

Name: Clay
Age: 25
PK: True

When we define Police, we put the class name to be inherited – here it is of course the Human category.

Then we use super().init() to put us into the basic properties of human beings, and then give Police the new attribute of the class power of this profession.

In the implementation part below, we only build clay as the Police category, but we can see that this new category (Police) has the same attributes and functions as the old category (Human).

So do you have a little understanding of the basic class operation?


Impression

I finally wrote the notes for the last class. Learning the Python class is not only a milestone in Python learning, but also a milestone in my personal record.

This is my first series of articles.

Python has a lot to learn. As an easy-to-use dynamic programming language, it has the advantages of ease of development, rapid writing, numerous packages, etc. However, because of GIL (Global Interpretation Lock), Python can’t write really efficient multi-threads. Program.

But even so, I still think that Python has won development time for programmers.

There are still a lot of things to learn in Python, please forgive me for not covering all areas. But from now on, I will continue to introduce a variety of Python applications.

That’s all very interesting topics.

I hope that you can also visit my blog and I will not correct your mistakes. Thank you!


References


Read More

Leave a Reply