This article introduces “object oriented” programming in Python. Published on my public account: Pythonic

For a better reading experience

Python3 base 10 “object oriented” programming

directory

1, the basic concept of object-oriented class instantiation of a class or object class attribute relationship between class and class 2, custom classes Create a custom class Create a class instance call class variable attributes Check the operation of a class called class methods attribute Using class and instance to specify a default value to modify attribute values 3, three common object-oriented inheritance to create subclasses Define new properties and methods for subclasses (extend is derived) Override methods of the parent class in subclasses (Override) Polymorphic and encapsulate instances as variable properties 4. Import classes Import a single class Import multiple classes from a module Import the entire module Import all classes in the moduleCopy the code

1. Basic concepts of object orientation

class

Things that have many characteristics in common can be thought of as templates. For example, the tank class positioned in a king yao below; Car classes; Dogs.

Class instantiation or object

Something concrete has its own characteristics. For example, zhu Bajie, Chang ‘e, Sun Ce, etc. are positioned as tank heroes in the above picture; BMW, Audi, Ferrari, etc.; Dog class 101 dalmatians, prosperous wealth, lai Fu, etc.

Attributes of a class

It can be divided into variable attributes (usually nouns, such as Breed, Size, Age and Color in the DOG class below) and method attributes (subfunctions, such as Eat, Sleep, Sit and Run).

Relationships between classes

The subclass directly owns the attributes and methods of the parent class, which is called inheritance. For example, the hero parent class has the attributes of damage, movement and control, while the tank and warrior subclasses inherit directly. Subclasses can customize the attributes of their parent class, called extend. For example, the tank subclass defines the control for falling from the sky, and the shooter defines the shot for sniping from thousands of miles. Subclasses can override attributes of their parent class, called overrides, such as tanks focusing on control, shooters focusing on damage, and so on.


2. Custom classes

Create custom classes

grammar

classThe name of the class(a):
"" class Description document ""The class bodyCopy the code

Create a Dog class

class Dog(a):# Capitalized names in Python refer to classes; Define a Dog class;
    """ Simulated dog """The #Dog class specification document describes the functionality of the Dog class.
    
    "" define the class constructor. ""
    def __init__(self,name,age):
        ##__init__
        # init, not int; Init has two underscores before and after it;
        Define "each instance's own characteristics";
        The functions in the # class are called methods, and __init__ is a special method that is automatically executed by Python every time an instance of the Dog class is created;
        
        ##self
        The parameter self is essential and must precede other parameters;
      Automatically pass the instance itself to self as the first argument to __init__ on instantiation;
        # When python calls the __init__() method to create an instance of the Dog class, self is the instance;
        Every method call associated with a class automatically passes the argument self, which is a reference "to the instance itself", giving the instance access to "properties and methods in the class".
        
        """ Define Dog class variable properties name, age"""
        Variables prefixed with self are called Dog class variable attributes (nouns) and are accessible to all methods and any instance of the Dog class.
        self.name = name        
        self.age = age
    
    Define the method properties of the Dog class, which are child functions.
    def sit(self):
        """ Sit Method for Simulating the sitting of a dog """
        print(self.name.title() + " is now sitting.")The name variable property of the Dog class is accessed in the sit method
    def roll_over(self):
        """ Roll_over method to simulate a dog roll """
        print(self.name.title()+"Rowlled over!")The name variable property of the Dog class is accessed in the #roll_over method
Copy the code

Creating a class instance

Syntax: class name (parameter); Create my_dog instance of the Dog class.

my_dog = Dog("cai wang".6)
Dog.__init__(" CAI wang",6)
Create a my_dog instance with name 'CAI Wang' and age 6;
__init__() creates my_dog with name 'CAI wang' and age 6;

__init__() returns (method __init__() does not explicitly contain a return statement) a dictionary-like object that stores properties and methods belonging to my_dog.
my_dog.__dict__
Copy the code

{‘name’: ‘cai wang’, ‘age’: 6}

Invoke class variable properties

Syntax: Name of the instance object. Variable attribute name

print("My dog's name is " + my_dog.name.title() + ".")#my_dog.name
print("My dog is " + str(my_dog.age) + " years old.") 
Copy the code

My dog’s name is Cai Wang.

My dog is 6 years old.

Invoke class method properties

Syntax: Name of the instance object. To call a method, specify the instance name (in this case, my_dog) and the method to call, separated by a period.

my_dog.sit()Call sit
my_dog.roll_over()# call the roll_over method
Copy the code

Cai Wang is now sitting. Cai Wang Rowlled over!

Class view operations

Dir (class name)# return a list of class attributes and methods Class name. Name# the name of the class (string). Doc# the documentation of the class. Base# the name of the first parent class of the class The class of the instance (only in the new class)

Use classes and instances

After the class is written, the rest of the work is to create instances of the class. Modify instance properties (either by directly modifying instance properties or by authoring methods).

class Car(a):
    """ Simulated car """
    def __init__(self, make, model, year):
        """ Initializes car properties """
        self.make = make
        self.model = model
        self.year = year
    def get_descriptive_name(self):
        "" return complete description. ""        
        long_name = "".join((str(self.year),self.make,self.model))# Access variable properties in method properties self.make, etc.
        return long_name.title()
my_car = Car("audi"."a4"."2020")Create an instance of Car
print(my_car.get_descriptive_name())# Call get_descriptive_name()
Copy the code
  • Specify default values for properties

Every attribute in a class must have an initial value, and if you set an initial value for an attribute in the __init__() method, you do not need to specify the parameter of that attribute in the __init__() parentheses.

class Car(a):
    """ Simulated car """
    def __init__(self, make, model, year):The default odometer_reading parameter is not set in parentheses.
        """ Initializes car properties """
        self.make = make
        self.model = model
        self.year = year        
        self.odometer_reading = 0# create default property odometer_reading and set the default value to 0.
    def get_descriptive_name(self):
        "" return complete description. ""
        To access the value of the attribute in this method, we use self.make, self.model, and self.year.
        long_name = "".join((str(self.year),self.make,self.model))
        return long_name.title()
    
    def read_odometer(self):
        """ Print a message indicating car mileage. """
        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() 
Copy the code

2016 Audi A4

This car has 0 miles on it.

  • Modifying property values

Modify directly through the instance The easiest way to modify the value of a property is to access it directly through the instance.

class Car(a):
    """ Simulated car """
    def __init__(self, make, model, year):
        """ Initializes car properties """
        self.make = make
        self.model = model
        self.year = year
        
        self.odometer_reading = 0#
    def get_descriptive_name(self):
        "" return complete description. ""
        long_name = "".join((str(self.year),self.make,self.model))
        return long_name.title()
    
    def read_odometer(self):
        """ Print a message indicating car mileage. """
        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# change odometer_reading to 23 in my_new_car
my_new_car.read_odometer()
Copy the code

2016 Audi A4

This car has 23 miles on it.

Set by method

class Car(a):
    """ Simulated car """
    def __init__(self, make, model, year):
        """ Initializes car properties """
        self.make = make
        self.model = model
        self.year = year        
        self.odometer_reading = 0
    def get_descriptive_name(self):
        "" return complete description. ""
        long_name = "".join((str(self.year),self.make,self.model))
        return long_name.title()    
    def read_odometer(self):
        """ Print a message indicating car mileage. """
        print("This car has " + str(self.odometer_reading) + " miles on it.")
        
    def update_odometer(self, mileage):Define the update_odometer method to modify the default value of the property
        "" sets the odometer reading 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)The update_odometer() method is called and is supplied with argument 23.
my_new_car.read_odometer()
Copy the code

2016 Audi A4

This car has 23 miles on it.

Incrementing by method (adding a specific value)

class Car(a):
    """ Simulated car """
    def __init__(self, make, model, year):
        """ Initializes car properties """
        self.make = make
        self.model = model
        self.year = year        
        self.odometer_reading = 0
    def get_descriptive_name(self):
        "" return complete description. ""
        long_name = "".join((str(self.year),self.make,self.model))
        return long_name.title()
    
    def read_odometer(self):
        """ Print a message indicating car mileage. """
        print("This car has " + str(self.odometer_reading) + " miles on it.")
        
    def update_odometer(self, mileage):
        "" sets the odometer reading to the specified value ""
        self.odometer_reading = mileage
        
    def increment_odometer(self, miles):
        "" increases the odometer reading by a specified amount ""
        self.odometer_reading += miles
my_used_car = Car('subaru'.'outback'.2020)
print(my_used_car.get_descriptive_name())

my_used_car.update_odometer(23500)
my_used_car.read_odometer()

my_used_car.increment_odometer(100)The #increment_odometer method increments the mileage attributes.
my_used_car.read_odometer()
Copy the code

2020 Subaru Outback

This car has 23500 miles on it.

This car has 23600 miles on it.


3. Three commonalities of object orientation

Polymorphism, inheritance, encapsulation

inheritance

The main reason for inheritance is to avoid code duplication, subclasses can take all the attributes from their parents, they don’t have to start from scratch; When a class (subclass or derived class) inherits from another class or more classes (superclass, base class, parent class, or superclass), the subclass gets all the attributes and methods of the parent class and can define its own attributes and methods.

  • Create a subclass

To subclass ElectricCar from the parent class we created earlier, we need only define electric car-specific properties and methods. The other properties and methods inherit from the Car class.

## Given the parent class
The parent class must precede the child class.
class Car(a):
    """ Simulated 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 = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")
    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading += mile
        
        
Create subclass ElectricCar
class ElectricCar(Car):When you define a subclass, you must specify the name of the parent class in parentheses.
    "" Subclass ElectricCar inherits parent class Car.
    def __init__(self, make, model, year):
        """ Initializes the properties of the parent class """
        super().__init__(make, model, year)
        The #super (from superclass) method lets subclasses inherit the methods of their parent class.
        #super() helps to associate the parent and subclasses, that is, ElectricCar subclasses call __init__() of the parent class's Car method.

my_tesla = ElectricCar('tesla'.'model s'.2016)
print(my_tesla.get_descriptive_name())   
Copy the code

2016 Tesla Model S

  • Define new properties and methods for subclasses (extend is derived)

Add battery this special variable attribute to electric car, and describe the method of this attribute. We will store the battery capacity and write a method to print the battery description:

class Car(a):
    """ Simulated 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 = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")
    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading += mile
        
class ElectricCar(Car):
    """ Simulated electric vehicle """
    def __init__(self, make, model, year):
        "" The uniqueness of electric vehicles inherits the attributes of the parent class and defines the unique attributes of electric vehicles. ""
        super().__init__(make, model, year)# Inherit superclass attributes
        self.battery_size = 70 # subclass battery_size new property, assign 70;
    def describe_battery(self):Description (describe_battery)
        """ Prints a message describing the battery capacity """
        print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla = ElectricCar('tesla'.'model s'.2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
Copy the code

2016 Tesla Model S

This car has a 70-kWh battery.

  • Overriding a parent class method in a subclass (override)

Any method of the parent class can be overridden to make it match the child class, which has the same name as the overridden method in the parent class, but only the overridden method is used in the child class.

class Car(a):
    """ Simulated 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 = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")
    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading += mile
    def fill_gas_tank(self):Override this method in a subclass
        """ The car has a gas tank. ""
        print("This car needs a gas tank!")   

class ElectricCar(Car):
    """Represent aspects of a car, specific to electric vehicles."""
    def __init__(self, make, model, year):
        The uniqueness of the electric vehicle initializes the attributes of the parent class, and then initializes the attributes unique to the electric vehicle.
        super().__init__(make, model, year)
        self.battery_size = 70
        
    def describe_battery(self):
        """ Prints a message describing the battery capacity """
        print("This car has a " + str(self.battery_size) + "-kWh battery.")
        
    def fill_gas_tank(self):
        # This overridden method is used only in subclasses, although it has the same name as the parent method.
        """ Electric cars don't have fuel tanks. ""
        print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla'.'model s'.2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()Call fill_gas_tank in ElectricCar instead of fill_gas_tank in Car.
Copy the code

2016 Tesla Model S

This car has a 70-kWh battery.

This car needs a gas tank!

  • Treat the instance as a variable property

When you use code to simulate the real thing, you may find yourself adding more and more detail to your classes: property and method lists and files get longer and longer. In this case, part of the class might need to be extracted as a separate class. You can break up large classes into smaller classes that work together.

class Car(a):
    """ Simulated 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 = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")
    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading += mile
    def fill_gas_tank(self):
        """ The car has a gas tank. ""
        print("This car needs a gas tank!")  

A new class called Battery is defined
class Battery(a):
    """ A simple attempt to simulate the battery of an electric vehicle ""
    def __init__(self, battery_size=70):
        "" initialize battery properties ""
        self.battery_size = battery_size
    def describe_battery(self):
        """ Prints a message describing the battery capacity """
        print("This car has a " + str(self.battery_size) + "-kWh battery.")
    def get_range(self):
        """ Print a message indicating battery range. """
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
            range = 270
        message = "This car can go approximately " + str(range)
        message += " miles on a full charge."
        print(message)

class ElectricCar(Car):
    """ What makes electric cars unique ""
    def __init__(self, make, model, year):
        Initialize the attributes of the parent class, and then initialize the attributes specific to the electric vehicle.
        super().__init__(make, model, year)
        self.battery = Battery()Each ElectricCar instance contains an automatically created Battery instance
my_tesla = ElectricCar('tesla'.'model s'.2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()The describe_battery method is called using the car attribute battery
my_tesla.battery.get_range()Call get_rang from the car's battery property
Copy the code

2016 Tesla Model S

This car has a 70-kWh battery.

This car can go approximately 240 miles on a full charge.

Polymorphism and encapsulation

Slightly (occupy pit first)


4. Import classes

Store the classes in modules (files ended with.py), and then import the required modules in the main program.

Importing a single class

Build the car. Py module: Create a file called car. Py and enter the following code for the car class.

 ##car.py
A class that can be used to represent an automobile.
Module documentation
class Car(a):
    """ A simple attempt to simulate a car. """
    def __init__(self, make, model, year):
        """ Initializes the properties describing the car """
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def get_descriptive_name(self):
        """ Returns a neat descriptive name """
        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):
        """ Sets the odometer reading to the specified value and refuses to dial the odometer back """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        "" increases the odometer reading by a specified amount ""
        self.odometer_reading += miles
Copy the code

Build the main program and import the Car class into the main program. This method makes the host program clean.

from car import CarOpen the car module and import the car class.
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()
Copy the code

2016 Audi A4

This car has 23 miles on it.

Import multiple classes from a module

from car import Car, ElectricCar
Copy the code

Import the entire module

import car
Copy the code

Import all classes in the module

fromModule nameimport *
Copy the code

The resources

Python Programming: From Getting Started to Practice www.cnblogs.com/Eva-J/artic…