This article is participating in Python Theme Month. See the link for details

Object-oriented programming is one of the most effective ways to write software. Creating objects from a class is called instantiation, which lets you use instances of the class.

Create and use classes

  • You can simulate almost anything using classes.
  • Let’s write a simple class that represents a puppyDog“, it refers not to any particular puppy, but to any puppy.

createDogClass:

class Dog:
    """ A simple attempt to simulate a puppy." ""
    def __init__(self, name, age) :
        """ Initializes the properties name and age." ""
        self.name = name
        self.age = age
    
    def sit(self) :
        """ Simulate a puppy crouching when commanded. "" ""
        print(f"{self.name} is now sitting.")

    def roll_over(self) :
        """ Simulating a puppy rolling when ordered." ""
        print(f"{self.name} rolled over!")
Copy the code
  • By convention, capitalized names in Python refer to classes.
  • There are no parentheses in this class because the class is being created from whitespace.

methods__init__()

  • The functions in a class are called methods.
  • methods__init__()Is a special method that Python automatically runs whenever you create a new instance of the Dog class.
  • In order toselfThe prefixed variable is available to all methods in the class and can be accessed through any instance of the class. This variable, which can be accessed by instance, is calledattribute.

Create an instance based on the class

  • Think of a class as an illustration of how to create an instance.
  • Let’s create an example that represents a specific puppy:
class Dog:
    """ A simple attempt to simulate a puppy." ""
    def __init__(self, name, age) :
        """ Initializes the properties name and age." ""
        self.name = name
        self.age = age
    
    def sit(self) :
        """ Simulate a puppy crouching when commanded. "" ""
        print(f"{self.name} is now sitting.")

    def roll_over(self) :
        """ Simulating a puppy rolling when ordered." ""
        print(f"{self.name} rolled over!")

my_dog = Dog('Willie'.6)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} year old.")
Copy the code
  • It is common to think of uppercase names (such as Dog) as referring to classes, and lowercase names (such as my_dog) as referring to instances created from classes.
  1. To access attributes
    • To access the properties of an instance, use a period notation.my_dog.name
  2. A method is called
    • Once you have created an instance from the Dog class, you can use the period notation to invoke any method defined in the Dog class.my_dog.sit()
  3. Create multiple instances
    • You can create as many instances of the class as you need.

Use classes and instances

  • Classes can be used to simulate many real-world scenarios.

Car

  • Let’s write a class that represents a car:
class Car:
    """ 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
    
    def get_descriptive_name(self) :
        """ Returns neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

my_new_car = Car('audi'.'a4'.2019)
print(my_new_car.get_descriptive_name())
Copy the code
  • To make this class more interesting, let’s add a property that changes over time to store the total mileage of the car.

Specify default values for properties

  • When creating an instance, some properties can be defined in a method instead of a parameter__init__()To specify a default value for it.
class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

my_new_car = Car('audi'.'a4'.2019)

print(my_new_car.get_descriptive_name())

my_new_car.read_odometer()
Copy the code

Modifies the value of an attribute

  • We can modify the value of a property in three ways: directly by instance, by method setting, and by method incrementing (adding a specific value).
  1. Modify the value of the property directly
class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

my_new_car = Car('audi'.'a4'.2019)

print(my_new_car.get_descriptive_name())

my_new_car.odometer_reading = 23

my_new_car.read_odometer()
Copy the code
  1. Method to modify the value of a property
  • It helps to have a way to update attributes for you. Instead of accessing the property directly, you can pass the value to a method that updates it internally.
class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        Sets the odometer reading to the specified value. ""
        self.odometer_reading = mileage

my_new_car = Car('audi'.'a4'.2019)

print(my_new_car.get_descriptive_name())

my_new_car.update_odometer(23)

my_new_car.read_odometer()
Copy the code
  • The methodupdate_odometer()To prohibit anyone from turning back the odometer reading.
class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        "" Sets the odometer reading to the specified value. Do not turn back the odometer reading. "" "
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

my_new_car = Car('audi'.'a4'.2019)

print(my_new_car.get_descriptive_name())

my_new_car.update_odometer(23)

my_new_car.read_odometer()
Copy the code
  1. Incrementing the value of an attribute through a method
  • Sometimes you need to increment the value of an attribute by a specific amount rather than setting it to a completely new value.
class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        "" Sets the odometer reading to the specified value. Do not turn back the odometer reading. "" "
        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

my_new_car = Car('subaru'.'outback'.2015)
print(my_new_car.get_descriptive_name())

my_new_car.update_odometer(23 _500)
my_new_car.read_odometer()

my_new_car.increment_odometer(100)
my_new_car.read_odometer()
Copy the code

inheritance

  • When writing a class, you don’t always want to start with whitespace. If the class you are writing is a special version of another ready-made class, use inheritance.
  • When a class inherits from another class, it automatically gets all the properties and methods of the other class.
  • The old class is called a parent class, and the new class is called a subclass.
  • A subclass inherits all the attributes and methods of its parent class and can also define its own attributes and methods.

Methods of subclasses__init__()

  • When you write a new class based on an existing class, you usually call the methods of the parent class__init__().
  • For example, an electric car is a special kind of car, inherited from an ordinary car:
class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        "" Sets the odometer reading to the specified value. Do not turn back the odometer reading. "" "
        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


class ElectricCar(Car) :
    """ What makes electric cars unique." ""
    def __init__(self, make, model, year) :
        """ Initializes the properties of the parent class." ""
        super().__init__(make, model, year)

my_tesla = ElectricCar('tesla'.'model s'.2019)
print(my_tesla.get_descriptive_name())
Copy the code
  • 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 in parentheses.
  • super()Is a special function that allows you to call methods of the parent class.
  • The superclass is also calledSuperclassesName,superAnd from there.

Define attributes and methods for subclasses

  • Having one class inherit from another allows you to add new properties and methods needed to distinguish subclasses from superclasses.
class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        "" Sets the odometer reading to the specified value. Do not turn back the odometer reading. "" "
        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


class ElectricCar(Car) :
    """ What makes electric cars unique." ""
    def __init__(self, make, model, year) :
        """ Initializes the properties of the parent class. Reinitialize the properties unique to the electric car. "" "
        super().__init__(make, model, year)
        self.battery_size = 75
    
    def describe_battery(self) :
        """ Prints a message describing the battery capacity. ""
        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()
Copy the code

Override the method of the parent class

  • Methods of the parent class can be overridden as long as they do not match the behavior of the object that the child class simulates.
  • To do this, you can define a method in a subclass with the same name as the parent class method you want to override. This way, Python will not consider the superclass method, but only the corresponding method you define in the subclass.

Use instances as properties

class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        "" Sets the odometer reading to the specified value. Do not turn back the odometer reading. "" "
        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


class Battery:
    """ A simple attempt to simulate the battery of an electric car." ""
    def __init__(self, battery_size=75) :
        """ Initializes the battery properties. ""
        self.battery_size = battery_size
    
    def describe_battery(self) :
        """ Prints a message describing the battery capacity. ""
        print(f"This car has a {self.battery_size}-kWh battery.")


class ElectricCar(Car) :
    """ What makes electric cars unique." ""
    def __init__(self, make, model, year) :
        """ Initializes the properties of the parent class. Reinitialize the properties unique to the electric car. "" "
        super().__init__(make, model, year)
        self.battery = Battery()

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

my_tesla.battery.describe_battery()
Copy the code
  • The following giveBatteryClass adds a method that reports the car’s range based on battery capacity:
class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        "" Sets the odometer reading to the specified value. Do not turn back the odometer reading. "" "
        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


class Battery:
    """ A simple attempt to simulate the battery of an electric car." ""
    def __init__(self, battery_size=75) :
        """ Initializes the battery properties. ""
        self.battery_size = battery_size
    
    def describe_battery(self) :
        """ Prints a message describing the battery capacity. ""
        print(f"This car has a {self.battery_size}-kWh battery.")

    def get_range(self) :
        if self.battery_size == 75:
            range = 260
        elif self.battery_size == 100:
            range = 315
        print(f"This car can go about {range} miles on a full charge.")


class ElectricCar(Car) :
    """ What makes electric cars unique." ""
    def __init__(self, make, model, year) :
        """ Initializes the properties of the parent class. Reinitialize the properties unique to the electric car. "" "
        super().__init__(make, model, year)
        self.battery = Battery()

my_tesla = ElectricCar('tesla'.'model s'.2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
Copy the code

To simulate the real

Import the class

  • Python allows you to store classes in modules, and then import the required modules into the main program.
  • incar.pyCreate aCarClass:
A class that can be used to represent an automobile. ""

class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        "" Sets the odometer reading to the specified value. Do not turn back the odometer reading. "" "
        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
  • inmy_car.pyIn the importCarClass:
from car import Car

my_new_car = Car('audi'.'a4'.2019)
print(my_new_car.get_descriptive_name())

my_new_car.odometer_reading = 23
my_new_car.read_odometer()
Copy the code
  • Importing classes is an effective way to program.
  • By moving the class into a module and importing it, you can still use all of its functionality, but the main program file becomes clean and easy to read.
  • This also lets you store most of your logic in separate files.
  • Once you’ve determined that the class works as you want it to, you can ignore the files and focus on the high-level logic of the main program.

Store multiple classes in a module

  • Although there should be some correlation between classes in the same module, you can store as many classes in a module as you need.
  • BatteryClasses andElectricCarClass to help simulate the car, add them to the module belowcar.pyIn:
A class that can be used to represent petrol-powered vehicles and electric vehicles. ""

class Car:
    """ 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 neat descriptive information." ""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self) :
        """ Print a message indicating the car's mileage." ""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage) :
        "" Sets the odometer reading to the specified value. Do not turn back the odometer reading. "" "
        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


class Battery:
    """ A simple attempt to simulate the battery of an electric car." ""

    def __init__(self, battery_size=75) :
        """ Initializes the battery properties. ""
        self.battery_size = battery_size
    
    def describe_battery(self) :
        """ Prints a message describing the battery capacity. ""
        print(f"This car has a {self.battery_size}-kWh battery.")

    def get_range(self) :
        if self.battery_size == 75:
            range = 260
        elif self.battery_size == 100:
            range = 315
        print(f"This car can go about {range} miles on a full charge.")


class ElectricCar(Car) :
    """ What makes electric cars unique." ""
    def __init__(self, make, model, year) :
        """ Initializes the properties of the parent class. Reinitialize the properties unique to the electric car. "" "
        super().__init__(make, model, year)
        self.battery = Battery()
Copy the code
  • You can create a new one calledmy_electric_car.pyFile, importElectricCarClass and create an electric car up:
from car import ElectricCar

my_tesla = ElectricCar('tesla'.'model s'.'2019')
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
Copy the code

Import multiple classes from a module

  • You can import as many classes as you need in the program file.
from car import Car, ElectricCar

my_beetle = Car('volkswagen'.'beetle'.'2019')
print(my_beetle.get_descriptive_name())

my_tesla = ElectricCar('tesla'.'roadster'.'2019')
print(my_tesla.get_descriptive_name())
Copy the code
  • When importing multiple classes from a module, separate them with commas.

Import the entire module

  • You can also import the entire module and use period notation to access the required classes.
import car

my_beetle = car.Car('volkswagen'.'beetle'.'2019')
print(my_beetle.get_descriptive_name())

my_tesla = car.ElectricCar('tesla'.'roadster'.'2019')
print(my_tesla.get_descriptive_name())
Copy the code

Import all classes in the module

  • This type of import is not recommended for two reasons.
  • One, if you just look at the beginning of the fileimportStatement, it is useful to have a clear idea of which classes your program uses. However, this type of import does not specify which classes in the module are used.
  • Second, this approach can also lead to name confusion. If you accidentally import a class with the same name as something else in the program file, you can cause hard-to-diagnose errors.

Import a module into another module

Use the alias

  • asStatements.

Customize the workflow

The Python standard library

  • The Python standard library is a set of modules that are included in all of our Python installations.
  • You can use any of the functions and classes in the standard library by including a simpleimportStatement.

Class coding style

  • Class names should be humped, with the first letter of each word in the class name capitalized rather than underlined. Instance and module names are lowercase and underlined between words.
  • For each class, a docstring should be included immediately after the class definition.
  • Each module should also contain a docstring describing what its classes can be used for.
  • Use blank lines to organize your code, but don’t abuse them. In a class, you can use an empty line to separate methods; In a module, you can use two blank lines to separate classes.
  • When you need to import both a standard library module and a module you wrote, write the import standard library module firstimportStatement, add a blank line, and write a code that imports your own moduleimportStatements.