preface
we explained the functions in Python in detail through three articles, including How to write functions,How to pass arguments as well as How to use arguments and keyword arguments . Starting from this article, I'll introduce you to classes in Python. First, I'll introduce you to create and use classes.
1, Create and use classes
using classes can simulate almost anything. Let's write a simple class Dog that represents a Dog - it doesn't represent a specific Dog, but any Dog. What do we know about most pet dogs? They all have names and ages; We also know that most puppies also squat and roll. Since most puppies have the above two information (name and age) and two behaviors (squatting and rolling), our Dog class includes them. This class lets Python know how to create objects that represent puppies. After writing this class, we will use it to create an instance that represents a particular Dog.
1. Create Dog class
each instance created from the Dog class will store the name and age. We have given each puppy the ability to sit () and roll_over (). The specific implementation is as follows:
class Dog(): """A simple attempt to simulate a puppy""" def __init__(self, name, age): """Initializing properties name and age""" self.name = name self.age = age def sit(self): """Simulate a dog squatting when ordered""" print(self.name.title() + " is now sitting.") def roll_over(self): """Simulate the dog rolling when ordered""" print(self.name.title() + " rolled over!")
there are many things to pay attention to here, but you don't have to worry. This article and the next two articles will have many similar structures, and we will have a lot of opportunities to get familiar with their structures. We defined a class named Dog. By convention, in Python, capitalized names refer to classes. The parentheses in this class definition are empty because we want to create this class from blank. We then write a document string to describe the functions of this class.
the functions in the class are called methods; Everything we learned about functions applies to methods. For now, the only important difference is the way we call methods. In addition, through__ init__ () is a special method. Whenever we create an instance based on the Dog class, python will run it automatically. In the name of this method, there are two underscores at the beginning and end, which is a convention to avoid name conflicts between Python default methods and ordinary methods.
we'll take the method__ init__ () is defined to contain three formal parameters: self, name and age. In the definition of this method, the formal parameter self is essential and must precede other formal parameters. Why must the formal parameter self be included in the method definition? Because Python calls this__ init__ () method to create a Dog instance, it will automatically pass in the argument self, which is a reference to the instance itself, so that the instance can access the properties and methods in the class. When we create a Dog instance, python will call the methods of the Dog class__ init__ (). We will pass the name and age to Dog() through the instance; Self is passed automatically, so we don't need to pass it. Whenever we create an instance based on the Dog() class, we only need to provide values for the last two formal parameters (name and age).
then, both variables we define have the prefix self. Variables prefixed with self can be used by all methods in the class. We can also access these variables through any instance of the class. self.name = name gets the value stored in the formal parameter name and stores it in the variable name, and then the variable is associated with the currently created instance. self.age = age works similarly. Variables that can be accessed through instances like this are called properties.
the Dog class also defines two other methods: sit () and roll_over(). Since these methods do not require additional information, such as name and age, they have only one formal parameter, self. The instance we will create later can access these methods, in other words, they all squat and roll. Currently, sit() and roll_ What over() does is limited. They just print a message indicating that the Dog is squatting or rolling. However, these methods can be extended to simulate the actual situation; If this class is included in a computer game, these methods will include code to create animation effects of Dog squatting and rolling. If this class is used to control the robot Dog, these methods will guide the robot Dog to squat and roll.
2. Create instances from classes
you can think of a class as a description of how to create an instance. The Dog class is a list of instructions that let Python know how to create an instance that represents a particular Dog. Let's create an instance representing a specific Dog. The specific implementation is as follows:
class Dog(): """A simple attempt to simulate a puppy""" def __init__(self, name, age): """Initializing properties name and age""" self.name = name self.age = age def sit(self): """Simulate a dog squatting when ordered""" print(self.name.title() + " is now sitting.") def roll_over(self): """Simulate the dog rolling when ordered""" print(self.name.title() + " rolled over!") my_dog = Dog('willie', 6) print("My dog's name is " + my_dog.name.title() + ".") print("My dog is " + str(my_dog.age) + "years old.")
the Dog class written in the previous example is used here. We asked Python to create a Dog named 'willie' and aged 6. When this line of code is encountered, python uses the arguments' William 'and 6 to call the methods in the Dog class__ init__ (). Method__ init__ () create an example representing a specific Dog and set the properties name and age with the values we provide. Method__ init__ () does not explicitly contain a return statement, but Python automatically returns an example that represents this. We store this instance in the variable my_ In Dog. The specific implementation results are as follows:
naming conventions are useful here: we can usually think that capitalized names (such as Dog) refer to classes, while lowercase names (such as my_dog) refer to instances created from classes.
1. Access properties
to access the properties of an instance, use the period notation. We wrote the following code to access my_ Value of dog attribute name:
my_dog.name
period notation is commonly used in Python. This syntax demonstrates how Python knows the value of an attribute. Here, python finds the instance my first_ Dog, and then find the attribute name associated with this instance. When this attribute is referenced in the dog class, self. Is used name. In addition, we use the same method to get the value of the attribute age. In the first print statement above, my_dog.name.title() will be my_ Change the attribute name value of dog, William, to uppercase; In the second print statement, str(my_dog.age) sets my_ The value 6 of the attribute age of dog is converted into a string.
2. Call method
after creating an instance from the Dog class, you can use the period notation to call any method defined in the Dog class. Let the Dog squat and roll as follows:
class Dog(): """A simple attempt to simulate a puppy""" def __init__(self, name, age): """Initializing properties name and age""" self.name = name self.age = age def sit(self): """Simulate a dog squatting when ordered""" print(self.name.title() + " is now sitting.") def roll_over(self): """Simulate the dog rolling when ordered""" print(self.name.title() + " rolled over!") my_dog = Dog('willie', 6) my_dog.sit() my_dog.roll_over()
to call a method, specify the instance name (here my_dog) and the method to call, and separate them with a period. Encountered code my_ Dog. When sit(), python looks for the method sit() in the class Dog and runs its code. Python interprets code in the same way_ Dog. roll_ over(). The specific implementation results are as follows:
this grammar is very useful. If appropriate descriptive names are assigned to attributes and methods, such as name, age, sit(), and roll_over(), even if it's a code block we've never seen before, we can easily infer what it does.
3. Create multiple instances
any number of instances can be created according to the class as required. Now create another one named your_dog instance, the specific implementation is as follows:
class Dog(): """A simple attempt to simulate a puppy""" def __init__(self, name, age): """Initializing properties name and age""" self.name = name self.age = age def sit(self): """Simulate a dog squatting when ordered""" print(self.name.title() + " is now sitting.") def roll_over(self): """Simulate the dog rolling when ordered""" print(self.name.title() + " rolled over!") my_dog = Dog('willie', 6) your_dog = Dog('lucy', 3) print("My dog's name is " + my_dog.name.title() + ".") print("My dog is " + str(my_dog.age) + "years old.") my_dog.sit() print("\nYour dog's name is " + your_dog.name.title() + ".") print("Your dog is " + str(your_dog.age) + "years old.") your_dog.sit()
in this example, we created two puppies, Willie and Lucy. Each dog is an independent instance with its own set of attributes, which can perform the same operation. The specific execution results are as follows:
even if we give the second puppy the same name and age, Python will still create another instance based on the Dog class. We can create any number of instances according to a class as needed, provided that each instance is stored in different variables or occupies different locations in the list or dictionary.
2, Using classes and instances
we can use to simulate many situations in the real world. After the class is written, we will spend most of our time using the instances created from the class. An important task we need to perform is to modify the properties of the instance. We can directly modify the properties of the instance, or we can write methods to modify them in a specific way.
1. Car class
next, we write a class representing cars, which stores information about cars and a method to summarize this information; The specific implementation is as follows:
class Car(): """A simple attempt to simulate a car""" def __init__(self, make, model, year): """Initialize the properties that describe the car""" self.make = make self.model = model self.year = year def get_descriptive_name(self): """Returns neat descriptive information""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name())
we first define the method__ init__ (). As in the previous Dog class, the first formal parameter of this method is self; We also include three other formal parameters in this method: make, model and year. Method__ init__ () accepts the values of these parameters and stores them in the properties of the instance created from this class. When creating a new Car instance, we need to specify its manufacturer, model and production year.
in addition, we define a name called get_descriptive_name(), which uses the attributes year, make and model to create a string describing the car, so that we don't need to print the value of each attribute separately. To access the value of the attribute in this method, we use self make,self.model,self.year. Finally, we create an instance based on the car class and store it in the variable my_new_car. Next, we call the get method_ descriptive_ Name (), indicating what kind of car we own. The specific implementation results are as follows:
to make this class more interesting, let's add a time-varying attribute to it, which stores the total mileage of the car.
2. Assign default values to attributes
Every attribute in a class must have an initial value, even if the value is 0 or an empty string. In some cases, if the default value is set, the method__ init__ It is feasible to specify such initial value in (); If we do this for a property, we don't need to include a formal parameter that provides an initial value for it. Let's add one named odometer_ The initial value of the reading property is always 0. We also added a file called read_ The usage of odometer () is used to read the odometer of the car. The specific implementation is as follows:
class Car(): """A simple attempt to simulate a car""" def __init__(self, make, model, year): """Initialize the properties that describe the car""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Returns neat descriptive information""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a message indicating the mileage of the car""" print("This car has " + str(self.odometer_reading) + " miles on it.") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
now, when Python calls a method__ init__ () to create an instance, the manufacturer, model, and year of manufacture are stored in the same way as in the previous example. Next, python will create a named odometer_ And set its initial value to 0. In addition, we also define a file called read_odometer() method, which allows you to easily learn the mileage of the car. At the beginning, the mileage of the car is 0, and the specific implementation results are as follows:
there are not many cars with an odometer reading of 0 when they are sold, so we need a way to modify the value of this attribute.
3. Modify the value of the attribute
you can modify the value of an attribute in three different ways; Modify directly through an instance; Set by method; Increment by method (increase a specific value). These methods are described in turn below.
1. Directly modify the value of the attribute
the easiest way to modify the value of an attribute is to access it directly through an instance. The following code directly sets the odometer reading to 23. The specific implementation is as follows:
class Car(): """A simple attempt to simulate a car""" def __init__(self, make, model, year): """Initialize the properties that describe the car""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Returns neat descriptive information""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a message indicating the mileage of the car""" print("This car has " + str(self.odometer_reading) + " miles on it.") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.odometer_reading = 23 my_new_car.read_odometer()
we use the period notation to directly access and set the attribute odometer of the car_ reading. This code allows Python to run my in an instance_ new_ Attribute odometer found in car_ Reading, and set the value of this attribute to 23. The specific execution results are as follows:
sometimes you need to access properties directly like this, but other times you need to write methods to update properties.
2. Modify the value of an attribute through the method
if there is a way to update properties for you, it will be of great benefit. In this way, we do not need to directly access the property, but can pass the value to a method, which can update it internally. The following example demonstrates an example called update_ The method of odometer() is implemented as follows:
class Car(): """A simple attempt to simulate a car""" def __init__(self, make, model, year): """Initialize the properties that describe the car""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Returns neat descriptive information""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a message indicating the mileage of the car""" print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """Set the odometer reading here to the specified value""" self.odometer_reading = mileage my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(23) my_new_car.read_odometer()
the only change made to the Car class is the addition of the method update_odometer(). This method accepts a mileage value and stores it in self odometer_ Reading. In addition, we called update_odometer() and provides it with an argument 23 (which corresponds to the formal parameter mile in the method definition). It sets the odometer reading to 23; And the method read_odometer() prints the reading, and the specific execution results are as follows:
we can also update the method_ Odometer () is extended to do additional work when modifying the odometer reading. Let's add some logic to prohibit anyone from callback the odometer reading. The specific implementation is as follows:
class Car(): """A simple attempt to simulate a car""" def __init__(self, make, model, year): """Initialize the properties that describe the car""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Returns neat descriptive information""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a message indicating the mileage of the car""" print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """ Set the odometer reading here to the specified value It is forbidden to callback the odometer reading here """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("Your can't roll back an odometer!") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(23) my_new_car.read_odometer()
now, update_odometer() checks whether the specified reading is reasonable before modifying the attribute. If the newly specified mileage is greater than or equal to the original mileage (self.odometer_reading), change the odometer reading to the newly specified mileage, otherwise a warning will be issued indicating that the odometer cannot be pulled back. The specific implementation results are as follows:
3. Increment the value of the attribute by method
sometimes you need to increment the attribute value by a specific amount instead of setting it to a new value. Suppose we buy a used car and increase the mileage by 100 miles from purchase to registration, the following method allows us to transfer this increment and increase the odometer reading accordingly, as follows:
class Car(): """A simple attempt to simulate a car""" def __init__(self, make, model, year): """Initialize the properties that describe the car""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Returns neat descriptive information""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a message indicating the mileage of the car""" print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """ Set the odometer reading here to the specified value It is forbidden to callback the odometer reading here """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("Your can't roll back an odometer!") def increment_odoemeter(self, miles): """Increase the odometer reading by the specified amount""" self.odometer_reading += miles my_used_car = Car('sunaru', 'outback', 2013) print(my_used_car.get_descriptive_name()) my_used_car.update_odometer(23500) my_used_car.read_odometer() my_used_car.increment_odoemeter(100) my_used_car.read_odometer()
our new method increment_odoemeter() accepts a number in units of miles and adds it to the column self odometer_ Reading. Then we created a used car - my_used_car. In addition, we call the method update_odometer() and pass in 23500, and set the odometer reading of this used car to 23500 Finally, we call increment_odoemeter() and pass in 100 to increase the driving distance of 100 miles from purchase to registration. The specific implementation results are as follows:
we can easily modify this method to prohibit the increment from being negative, so as to prevent someone from using it to dial the odometer back and forth. What we need to pay attention to here is that we can use a method similar to the above to control the way users modify the attribute value (if the odometer reading), but anyone who can access the program can modify the odometer to any value by directly accessing the attribute. To ensure safety, in addition to the basic inspection similar to the previous one, special attention should be paid to details.
summary
we explained the functions in Python in detail through three articles, including How to write functions,How to pass arguments as well as How to use arguments and keyword arguments . Starting with this article, I will introduce the classes in Python. This paper introduces the creation and use of classes, and introduces the examples of classes in detail with a case. Python is a language that pays attention to practical operation. It is the simplest and the best entry among many programming languages. When you learn this language, it's easier to learn java, go and C. Of course, Python is also a popular language, which is very helpful for the implementation of artificial intelligence. Therefore, it is worth your time to learn. We live and struggle. We work hard every day, study hard, and constantly improve our ability. I believe we will learn something. come on.