Classes are part of object-oriented programming. Object-oriented programming or OOP for short is dedicated to creating reusable code blocks called classes. When you want to use a class in your program, you create an object from the class, which is the origin of the term object-oriented. Python is not always object-oriented, but you will use objects in your projects. In order to understand classes, you need to understand some basic object-oriented terms.
Common terms
class: Class. The class is the main body of the code block, which defines the attributes and behaviors of the established model. This model can come from the real world, or it can be a virtual game.
attribute: attribute. It is a collection of a series of information. In a class, an attribute is usually a variable.
behavior: Behavior. Behavior is defined in the class, the part of the method. That is, part of the function defined in the class.
method: Method. The functions in the class are composed of behavior.
object: Object. Objects are instances of classes. An object contains the values of all attributes in the class. You can create any number of objects for a class.
Take a closer look at the Rocket class
We have learned the basic terminology of some classes, let us go back and analyze the Rocket class mentioned in the previous section.
__ init__() method
Define an initial code block as follows:
classRocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an(x,y) position.
self.x =0
self.y =0
The first line shows how the class is created. The keyword class tells Python to prepare to define a class. The naming rules for class names are the same as those for variables, but there is a well-established rule in Python that class names must be camel case. That is, the beginning of each word must be capitalized, and underscores are not allowed. The class name is immediately followed by a pair of parentheses. So far, the parentheses are empty. In the next study, it may contain a class. This class is the class on which the new class is based.
Functions with two underscores before and after are special-purpose functions built into Python. The init() function is a special function. When an object of a class is created, it is executed automatically. We can call it an initialization function to initialize some necessary properties before the object is used. In this example, the init() function initializes the x and y attributes.
The keyword self may be a bit difficult to understand. The word "self" refers to the current object. When you create a class, it can access any specified attributes in the class. Basically, all functions in the class require the self object as the first parameter, so they can access the properties in the class.
Now, let's look at the methods in the class!
A simple way
The following code defines a method in the Rocket class.
classRocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an(x,y) position.
self.x =0
self.y =0
def move_up(self):
# Increment the y-position of the rocket.
self.y +=1
Methods are functions in classes. So you can do anything the function can do in the method.
By default, every function needs to accept one parameter: self. It is a reference to the object calling this method. The self parameter allows you to access the properties of the calling object. In this example, self is used to access the y property of the Rocket object. When this method is called once, the y property of the object is increased by 1. In order to get a closer look at the operation of the method, carefully read the following codes and observe their output.
classRocket():
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self):
# Each rocket has an(x,y) position.
self.x =0
self.y =0
def move_up(self):
# Increment the y-position of the rocket.
self.y +=1
# Create a Rocket object, and have it start to move up.
my_rocket =Rocket()print("Rocket altitude:", my_rocket.y)
my_rocket.move_up()print("Rocket altitude:", my_rocket.y)
Create multiple objects
An important goal of object-oriented programming is to create reusable code. Once you have written the class, you can create any number of objects. Usually, the class is placed in a separate file and imported into the program when needed. So you can create a class library and reuse these classes in different programs.
Create multiple objects on a class, an example is as follows:
classRocket():
# Rocket simulates a rocket ship for a game,# Rocket
# or a physics simulation.
def __init__(self):
# Each rocket has an(x,y) position.
self.x =0
self.y =0
def move_up(self):
# Increment the y-position of the rocket.
self.y +=1
# Create a fleet of5 rockets, and store them in a list.
my_rockets =[]for x inrange(0,5):
new_rocket =Rocket()
my_rockets.append(new_rocket)
# Show that each rocket is a separate object.for rocket in my_rockets:print(rocket)
Content expansion:
Get to know classes and objects
Everything in python is an object, and the essence of types is classes, so, believe it or not, you have been using classes for a long time.
dict #Type dict is class dict
< class'dict'
d=dict(name='eva') #Instantiate
d.pop('name') #Send a message to d, execute the method pop of d
' eva'
Judging from the above example, a dictionary is a type of data structure. When I talk about a dictionary, you will know that it is something that is represented by {} and contains kv key-value pairs. It also has some methods of adding, deleting, modifying and checking. But when I talk about the dictionary, can you know what exactly is stored in the dictionary? No, so we say that for a class, it has the same characteristic attributes and methods.
The specific {'name':'eva'} dictionary, it is a dictionary, all methods of the dictionary can be used, and there are specific values in it, it is an object of the dictionary. The object is a concrete individual that already exists.
Let me give another example, which is more general. For example, if you have a zoo, and you want to describe this zoo, then every animal in the zoo is a kind, tiger, swans, crocodile, and bear. They all have the same attributes, such as height, weight, birth time and breed, as well as various actions, such as crocodile can swim, swan can fly, tiger can run, and bear can eat.
But these tiger bears are not a specific one, but a kind of animal. Although they all have height and weight, you have no way to determine what this value is. If you are given a specific tiger at this time and you are not dead, then you can measure his height and weigh him. Will these values become specific? Then the specific tiger is a specific instance and an object. More than this one. In fact, every specific tiger has its own height and weight, so every tiger is an object of the tiger category.
So far, this article on how to understand python object-oriented programming is introduced. For more detailed explanations of python object-oriented programming, please search ZaLou.Cn
Recommended Posts