Basic knowledge of Python -- class

    This article is the basic knowledge of Python (from entry to practice) - class. The basic knowledge of Python in this section mainly includes: creating and using classes, using classes and instances, inheritance, importing classes, and class coding styles.



       One of the most effective ways of writing software is object-oriented programming, in which we write classes that represent transactions and situations in the real world and create objects based on these classes. When writing a class, we define common behavior that a large class of objects has. When objects are created based on classes, each object automatically has this common behavior. Creating an object from a class is called instantiation, which allows us to use an instance of a class.

1. Create and use classes

   Almost anything can be mocked using classes. 1.1 below shows a simple example:

1.1 Create the Dog class

       Each instance created from the Dog class will store the name and age, and we give each puppy the ability to squat and roll over:

class Dog:
    """一次模拟小狗的简单尝试。"""

    def __init__(self,name,age):
        """初始化属性name和age。"""
        self.name = name #4
        self.age = age

    def sit(self):
        """模拟小狗收到命令时蹲下"""
        print(f'{self.name} is noe sitting.')

    def roll_over(self):
        '''模拟小狗收到命令时打滚'''
        print(f'{self.name} is rolled over!.')

       By convention, in Python, capitalized names refer to classes. There are no parentheses in this class definition because the class is being created from blank. The second line writes a docstring describing what the class does.

method_init_()

      Functions in a class are called methods. Everything you learned about functions applies to methods, the only important difference is how you call them. The method  _init_()  is a special method that Python runs automatically whenever a new instance of the Dog class is created. In the name of this method, there are two underscores at the beginning and two at the end, which is a convention to avoid name conflicts between Python default methods and ordinary methods. Make sure that _init()_   has two underscores on both sides, otherwise when the class is used to create an instance, this method will not be called automatically, causing hard-to-find errors.

       We define the method _init()_ to take three parameters: self, name, and age. self is required in this method and must precede the other parameters. The actual parameter self will be passed automatically when the python method is used to create a Dog instance. The method call associated with each instance automatically passes the argument self. It is a reference to the instance itself, giving the instance access to properties and methods in the class.

       Both variables defined at 4 have the prefix self. Variables prefixed with self are available to all methods in the class and can be accessed by any instance of the class. self.name = name Gets the value associated with the formal parameter name and assigns it to the variable name, which is then associated with the currently created instance. self.age = age works similarly. Variables accessible through instances like this are called properties .

       The Dog class also defines two additional methods: sit() and roll_over(). These methods require no additional information to execute, so they have only one formal parameter, self. Instances that will be created subsequently will have access to these methods, in other words, they will all squat and roll.

1.2 Create an instance based on a class

       Think of classes as instructions on how to create instances. The Dog class is a series of instructions that let Python know how to create an instance that represents a particular puppy.

Let's create an instance that represents a specific puppy:

class Dog:
     --snip--

my_dog = Dog('Willie',7)

print(f"My dog's name is {my_dog.name}." ) #2
print(f"My dog is {my_dog.age} years old.") #3

       The Dog class written in the previous example is used here. First let python create a puppy named "Willie" and age '7'. When the code is encountered, python calls the method _init_() of the Dog class with the arguments 'Willie' and 7 . The method _init_() creates an instance representing a particular puppy, and we assign this instance to the variable my_dog. Here, a naming convention is useful: it can often be assumed that a capitalized name (like Dog) refers to the class, while a lowercase name (like my_dog) refers to the instance created from the class.

1. Access properties

      To access properties of an instance, use period notation. 2 wrote the following code to access the value of the attribute name of my_dog:

my_dog.name

      Period notation is common in python, and this syntax demonstrates how python learns the value of an attribute. Here, python first finds the instance my_dog and then looks up the attribute name associated with that instance. When referencing this property in the Dog class, self.name is used. At 3, use the same method to get the value of the attribute age.

The output is a summary about my_dog:

 2. Call method

       After you create an instance of the Dog class, you can use period notation to call any method defined in the Dog class. Let's make the puppy squat and roll: 

class Dog:
     --snip--

my_dog = Dog('Willie',7)
my_dog.sit()
my_dog.roll_over()

      To call a method, specify the name of the instance (my_dog here) and the method to call, separated by a period. When the code my_dog.sit() is encountered, python looks for the method sit() in the class Dog and runs its code. Python interprets the code my_dog.roll_over() in the same way.

Willie did as we ordered:

 3. Create multiple instances

      You can create as many instances of a class as you need. Let's create another puppy instance named your_dog:

class Dog:
     --snip--

my_dog = Dog('Willie',7)
your_dog = Dog('Lucy',2)

print(f"My dog's name is {my_dog.name}." ) 
print(f"My dog is {my_dog.age} years old.")
my_dog.sit()

print(f"Your dog's name is {your_dog.name}." ) 
print(f"Your dog is {your_dog.age} years old.")
your_dog.sit()

       In this example two puppies are created, each a separate instance with its own set of properties capable of performing the same operations:

       Even if you assign the same name and age to the second puppy, python will still create another instance of the Dog class. We can create as many instances of a class as we want, provided that each instance is stored in a different variable, or occupies a different position in a list or dictionary.

2. Using classes and instances

      Classes can be used to simulate many scenarios of the real world. After the class is written, most of our time will be spent on creating instances from the class. One important task we need to perform is to modify the properties of the instance. You can directly modify the properties of the instance, or you can modify it in a specific way.

2.1 Car class

Let's write a class that represents a car. It stores information about cars, and has a method to aggregate this information:

class Car:
    """一次模拟汽车的简单尝试"""
    def __init__(self,make,model,year):  #1
        """初始化描述汽车的属性"""
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self):   #2
        """返回需要的描述性信息."""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
my_new_car = Car('audi','a4',2015)  #3
print(my_new_car.get_descriptive_name())

       The method _init_() is defined at 1. As in the previous Dog class, the first parameter of this method is self. The method also contains three other parameters: make, model, and year. The method _init_() takes the values ​​of these formal parameters and assigns them to attributes of instances created from this class. When creating a new car instance, you need to specify its manufacturer, model, and production year.

       At 2, a method called get_descriptive_name() is defined. At 3 an instance is created from the Car class and assigned to the variable my_new_car.

The result of the operation is as follows:

       To make this class more interesting, let's add a time-varying property to store the total mileage of the car.

2.2 Assign default values ​​to attributes

       When creating an instance, some attributes do not need to be defined through formal parameters, and default values ​​can be specified for them in the method _init_().

       Next add a property called odometer_reading whose initial amount is always 0. We also add a method called read_odometer() to read the car's odometer:

class Car:
    """一次模拟汽车的简单尝试"""
    def __init__(self,make,model,year):
        """初始化描述汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        """返回需要的描述性信息."""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self):
        """打印一条指出汽车里程的消息"""
        print(f"This cars has {self.odometer_reading} miles on it.")

my_new_car = Car('audi','a4',2015)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()

At the beginning the mileage of the car is 0:

 2.3 Modify the value of an attribute

       We can modify the value of a property in three ways: directly through the instance, set through a method, and incremented (increase a specific value) through a method. These methods are described in order below:

1. Directly modify the value of the attribute 

      To modify the value of a property, the easiest way is to access it directly through the instance. The following code directly sets the mileage to 23:

class Car:
    --snip--

my_new_car = Car('audi','a4',2015)
print(my_new_car.get_descriptive_name())

my_new_car.odometer_reading =23
my_new_car.read_odometer()

Output result:

     Sometimes you need to access properties directly like this, but sometimes you need to write methods that update properties.

2. Modify the value of the attribute through the method

      It would be nice to have a method to update the property value, so that instead of accessing the property directly, the value can be passed to the method and it will be updated internally. A method called uodate_odometer() is demonstrated below:

class Car:
    --snip--

    def update_odometer(self,mileage):
        """将里程数设置成为特定的值"""
        self.odometer_reading = mileage


my_new_car = Car('audi','a4',2015)
print(my_new_car.get_descriptive_name())

my_new_car.update_odometer(28)
my_new_car.read_odometer()

The output is as follows:

3. Increment the attribute value by method 

Sometimes a property is incremented by a specific amount instead of setting it to an entirely new value. Examples are as follows:

class Car:
    --snip--

    def increment_odometer(self,mils):
        """将里程碑增加指定的量"""
        self.odometer_reading += mils


my_new_car = Car('audi','a4',2015)
print(my_new_car.get_descriptive_name())

my_new_car.update_odometer(28_500)
my_new_car.read_odometer()

my_new_car.increment_odometer(100)
my_new_car.read_odometer()

The output is as follows:

 3. Inheritance

       When writing a class, you don't always have to start with a blank slate. Use inheritance when you want to write a class that is a specialized version of another existing class. When a class inherits another class, it will automatically get all the properties and methods of the other class. The original class is called the parent class, and the new class is called the child class. The subclass inherits all the properties and methods of the parent class, and can also define its own properties and methods.

3.1 Subclass method _init_()

       When writing a new class based on an existing class, the method _init_() of the parent class is usually called. This will initialize all properties defined in the superclass's _init_() method, allowing subclasses to include them. 

       The example is as follows: The electric car is simulated below, so a new class ElectricCar can be created on the basis of the previously created car class. This eliminates the need to write code for EV-specific properties and behaviors.

class Car:
    """一次模拟汽车的简单尝试"""
    def __init__(self,make,model,year):
        """初始化描述汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        """返回需要的描述性信息."""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self):
        """打印一条指出汽车里程的消息"""
        print(f"This cars has {self.odometer_reading} miles on it.")

    def update_odometer(self,mileage):
        """将里程数设置成为特定的值"""
        self.odometer_reading = mileage

    def increment_odometer(self,mils):
        """将里程碑增加指定的量"""
        self.odometer_reading += mils

class ElectricCar(Car):
    """电动汽车的独特之处"""

    def __init__(self,make,model,year):
        """初始化父亲的属性"""
        super().__init__(make,model,year)

my_tesla = ElectricCar('tesla','model s',2019)
print(my_tesla.get_descriptive_name())

       When creating a subclass, the parent class must be included in the current file and precede the subclass. When defining a subclass, you must specify the name of the parent class within parentheses. The method _init_() accepts the information needed to create a Car instance.

       super() is a special function that allows us to call a method of the parent class. This line of code tells python to call the method _init_() of the Car class, making the ElectricCar instance contain all the properties defined in this method. The parent class is also called the superclass (superclass), from which the name super comes.

       Apart from the method _init_(), EVs have no other specific properties and methods. For now, we just want to confirm that an electric car behaves like a regular car:

      The ElectricCar instance behaves like a Car instance, and you can now start defining properties and methods specific to electric cars.

3.2 Define properties and methods for subclasses

     Once you have one class inherit from another, you can add the new properties and methods needed to differentiate the subclass from the superclass.

     Let's add an electric vehicle-specific attribute (battery):

class Car:
    --snip--


class ElectricCar(Car):
    """电动汽车的独特之处"""

    def __init__(self,make,model,year):
        """初始化父亲的属性"""
        super().__init__(make,model,year)
        self.battery_size = 75

    def describe_battery(self):
        """打印一条描述电瓶的信息"""
        print(f"This car has a {self.battery_size}-kwh battery.")

my_tesla = ElectricCar('tesla','model s',2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()

The output is as follows:

 3.3 Override the method of the parent class

        For the method of the parent class, as long as it does not conform to the behavior of the object simulated by the subclass, it can be considered to be rewritten. To do this, a method with the same name as the superclass method to be overridden can be defined in the subclass. In this way, python will not consider this parent class method, but only focus on the corresponding method you defined in the subclass.

       Let's say the Car class has a method called fill_gas_tank() that is meaningless for an all-electric car and we want to override it. Here's a way to rewrite:

class ElectricCar(Car):
    --snip--
    
    def fill_gas_tank(self):
    """电动汽车没有油箱"""
    print("This car doesn't need a gas tank!")

        Now if someone calls the method  fill_gas_tank() on the electric car, python will ignore the method of the Car class and run the above code instead. When using inheritance, subclasses can retain the essence inherited from the parent class and get rid of unnecessary dross.

3.4 Using instances as attributes

       As you simulate the real thing with code, you may find yourself adding more and more detail to your classes: the list of properties and methods, and the files get longer and longer. In this case, it may be necessary to extract part of the class as a separate class. Large classes can be broken down into multiple smaller classes that work together.

For example, when adding details to the battery car class, we will find that it contains many properties and methods for car batteries. In this case, these properties and methods can be extracted and put into a class named Battery, and an instance of Battery can be used as a property of the battery car class:

class Car:
    --snip--

class Battry:
    """一次模拟电动汽车电瓶的简单尝试"""

    def __init__(self,battery_size=75):
        """初始化电瓶的属性。"""
        self.battery_size = battery_size

    def describe_battery(self):
        """打印一条描述电瓶容量的消息。"""
        print(f"This car has a {self.battery_size}-kwh battery.")

class ElectricCar(Car):
    """电动汽车的独特之处"""

    def __init__(self,make,model,year):
        """初始化父亲的属性"""
        super().__init__(make,model,year)
        self.battery = Battry()



my_tesla = ElectricCar('tesla','model s',2019)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()

       We define a new class called Battery, which does not inherit from any class. Added a property called self.battery to the ElectricCar class. This line of code tells python to create a new Battery instance and assign that instance to the property self.battery . This will be done whenever the method _init_() is called. So now every ElectricCar instance contains an automatically created Battery instance.

4. Import class

      As functionality is added to classes, the file can become very long, even with inheritance. In keeping with the general philosophy of python, you should keep your files as clean as possible. Python helps with this, allowing classes to be stored in modules and then imported in the main program as needed.

4.1 Importing a single class

      Let's create another file and import the previous Car class:

from car import Car

      The import statement tells Python to open the module car and import the Car class in it.

4.2 Storing multiple classes in one module

     You can store as many classes as you want in a module, although there should be some dependency between classes in the same module.

4.3 Importing multiple classes from a module

    You can import as many classes as you want in a program file. Examples are as follows:

from car import Car,ElectricCar

      When importing multiple classes from a module, separate the classes with commas. Once the necessary classes are imported, you can create as many instances of each class as you need.

4.4 Importing the whole module

      You can also import entire classes and then use period notation to access the required classes. Examples are as follows:

import car

my_li = car.Car()
my_hua = car.ElectricCar()

4.5 Import all classes of the module (not recommended)

from module_name import *

4.6 Using aliases

from car import Car as C

4.7 Class coding style

       Class names should be camel-cased, i.e. capitalize every word in the class name without underscores. Both instance and module names are in lowercase, with underscores between words.

      For each class, a docstring should be included immediately following the class definition. Briefly describe what the class does, and follow the formatting conventions used when writing a function's docstring. Each module should also contain a docstring describing what the classes in it can be used for.


Today's learning summary is here! If you have any questions, you can leave a message in the comment area~

If it helps everyone, you can click three times + pay attention to support~

Reference study books: Python programming from entry to practice (Second Edition)


Series Article Directory

Python basic knowledge points--variables and simple data types

Python basic knowledge points--listPython
basic knowledge points--traverse lists, slices, tuples

Basic knowledge of Python -- if statement

Basic knowledge of Python -- dictionary

Basic knowledge of Python -- user input and while loop

Basic knowledge of Python -- function

Guess you like

Origin blog.csdn.net/m0_57787115/article/details/129598486