leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python Classes and Objects

Estimated reading: 6 minutes 67 views

In the Python language, almost everything can be represented by objects. Object- Oriented Programming (OOP) is a way of designing and writing programs.

In fact, in the previous study, we have already used objects. Data types such as numbers, strings, dictionaries and lists are all objects. Objects often contain various attribute values ​​and methods, and various data types have their built-in functions, such as the upper() function that capitalizes the first letter of all words in a string, and the keys() function that retrieves all the keys of the dictionary. Both are built-in functions of their respective data types.

In Python, all variables are also objects, but variables usually have only one value. For example, strings hold a set of characters, integers hold a number, and lists hold a set of elements of an item. However, objects are a better model of the real world than variables, because we are often exposed to more than one side.

For example, when building a racing game, we can represent each car as an object that has many of the properties a car needs, such as color, number of tires, engines, seats, sound, etc., and it can have many more methods, such as drawing cars, moving cars, etc. Then, we can create multiple car objects, all of which have these properties and methods.

Python class and object creation

How exactly do we create objects? To create an object, we first need a class. A class is like a rubber stamp, and an object is an instance of the stamp. A class is a blueprint or template for creating objects of the same type and determines what kind of objects can be obtained. For example, if we create a Dog class with a name attribute and an age attribute, then all objects created through this Dog class will have an age attribute and a name attribute – objects of this type will not have many or no attributes. few.

In summary, a class is an OOP tool that enables programmers to abstract the problem they want to study. In OOP, abstraction is the use of programming objects to represent the behavior of objects in the real world. Program objects also don’t need to have all the details of real-world objects. For example, if the Dog object only needs to say hello, the Dog class needs only one method, SayHello. The OOP abstraction omits a lot of things that real-world puppies still need to do, such as eating, drinking, and laughing, which makes programming logic relatively simple.

Let’s start by creating a simple class Dog that contains many properties of a dog.

class Dog:
    name=None
    legs=None
    age=None
    gender=None
    isCute=None

Next, we want to create an object, that is, to create an instance of the Dog class dog1, we can use dot notation .to access the properties of the object and assign values ​​to it.

dog1=Dog()
dog1.name="Wang Wang"
dog1.legs=4
dog1.age=2
dog1.gender="Boy"
dog1.isCute=True

Then, you can access the properties of this object.

print("The dog name is "+dog1.name+".")
print("The dog is a "+dog1.gender+".")
print("It is "+str(dog1.age)+" years old.")
if dog1.isCute==True:
    print("It is cute.")
else:
    print("It is not cute.")

Finally, the results obtained by running the program are shown in Figure 1.

Python class and object creation
figure 1

Python adds methods to objects

In the previous example, we created several properties in which we stored values ​​of different data types. We can also add functions to a class, note that the functions of a class are called methods. In fact, we’ve used several built-in methods, such as the upper() method that makes all letters of a string uppercase.

Now, let’s see how to create our own method. Let’s take the previous Dog class as an example and add a SayHello method to it.

class Dog:
    name=None
    legs=None
    age=None
    gender=None
    isCute=None  
    def SayHello(self):
        print("Woof...Woof")
        print("My name is "+self.name+".")
        print("I am a "+self.gender+".")
        print("I want to play with you.")

We added a new method, SayHello, and this method also has a parameter called self. The self is a keyword that represents a reference to the object itself, through which we can refer to any member of the class. For example, when calling the Hello method on a Dog object, self refers to the Dog object, so self.name refers to Dog.name.

Let’s see how to create an instance of this class.

dog1=Dog()
dog1.name="Wang Wang"
dog1.gender="Boy"
dog1.SayHello()

We created an instance dog1 of the Dog class, and then assigned values ​​to its properties name and gender, and then called the SayHello method of this class to print out the content of the dog’s greeting. The result of the program running is shown in Figure 2.

Python adds methods to objects
figure 2

Python uses constructors to create objects

In Python, classes have a special function called a constructor, which is automatically called every time an instance of the class is created. The name of the constructor method is __init__(), with two underscores at the beginning and two at the end, a convention used to distinguish Python’s default methods from normal methods.

We can pass parameters to the __init__() method so that when the instance is created, the properties can be set to the desired values. Taking the Dog class as an example, this time we need to assign values ​​to the attributes name and gender when calling the constructor. Then call the Hello method directly to see if the passed parameter is assigned to the property.

class Dog:   
    legs=None
    age=None   
    isCute=None  
    def __init__(self, name, gender):
        self.name=name
        self.gender=gender
    def Hello(self):
        print("Woof...Woof")
        print("My name is "+self.name+".")
        print("I am a "+self.gender+".")
        print("I want to play with you.")

Now every time we create an instance of the Dog class, the constructor will remind us to enter the parameters name and gender, as shown in Figure 3.

Python uses constructors to create objects
image 3
We create two instances of the Dog class, one is dog1 and the other is dog2. Then call their Hello() method respectively, and you will get different results, as shown in Figure 4.

Python uses constructors to create objects

Leave a Comment

CONTENTS