Python Programming: from introduction to practice reading notes: Chapter 9 classes

catalogue

Chapter 9 class

9.1 creating and using classes

9.1.1 create Dog class

9.1.2 create instances based on classes

9.2 use classes and instances

9.2.1 Car

9.2.2 assigning default values to attributes

9.2.3 modifying attribute values

9.3 succession

9.3.2 define attributes and methods for subclasses

9.3.3 method of overriding parent class

9.3.4 using instances as attributes

9.3.5 simulated object

9.4 import class

9.4.1 importing a single class

9.4.2 storing multiple classes in one module

9.4.3 importing multiple classes from a module

9.4.4 import the whole module

9.4.5 import all classes in the module

9.4.6 importing one module into another

9.4.7 using aliases

9.4.8 custom workflow

9.5 Python standard library

Class 9.6 coding style

Chapter 9 class

9.1 creating and using classes

9.1.1 create Dog class

class Dog:
    """A simple attempt to simulate a dog."""

    def __init__(self, name, age):
        """Initialize properties name and age. """
        self.name = name
        self.age = age

    def sit(self):
        """Simulate a dog squatting when ordered."""
        print(f"{self.name} is now sitting.")

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

9.1.2 create instances based on classes

class Dog:
    """A simple attempt to simulate a puppy."""

    def __init__(self, name, age):
        """Initialize properties name and age. """
        self.name = name
        self.age = age

    def sit(self):
        """Simulate a dog squatting when ordered."""
        print(f"{self.name} is now sitting.")

    def roll_over(self):
        """Simulate a dog 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} years old.")
My dog's name is Willie.
My dog is 6 years old.
my_dog = Dog('Willie', 6)
my_dog.sit()
my_dog.roll_over()
Willie is now sitting.
Willie rolled over!
my_dog = Dog('Willie', 6)
your_dog = Dog('Lucy', 3)

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"\nYour dog's name is {your_dog.name}.")
print(f"Your dog is {your_dog.age} years old.")
your_dog.sit()
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

Your dog's name is Lucy.
Your dog is 3 years old.
Lucy is now sitting.

9.2 use classes and instances

9.2.1 Car

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):
        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())
2019 Audi A4

9.2.2 assigning default values to attributes

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

    def read_odometer(self):
        """Print a message indicating the mileage of the car."""
        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()
2019 Audi A4
This car has 0 miles on it.

9.2.3 modifying attribute values

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()
2019 Audi A4
This car has 23 miles on it.
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):
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

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

    def update_odometer(self, mileage):
        """Set 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()
2019 Audi A4
This car has 23 miles on it.
    def update_odometer(self, mileage):
        """
        Set the odometer reading to the specified value.
        It is forbidden to callback the odometer reading.    
        """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print('You can\'t roll back an odometer!')
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):
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

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

    def update_odometer(self, mileage):
        """
        Set the odometer reading to the specified value.
        It is forbidden to callback 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):
        """Increase the odometer reading by the specified amount."""
        self.odometer_reading += miles


my_new_car = Car('audi', 'a4', '2019')
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()
2019 Audi A4
This car has 23500 miles on it.
This car has 23600 miles on it.

9.3 succession

When a class inherits from another class, it will automatically get all the properties and methods of the other class. The original class is called the parent class, while the new class is called the child class. Subclasses inherit all the properties and methods of the parent class, and can also define their own properties and methods.

class ElectricCar(Car):
    """The uniqueness of electric vehicles."""

    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())
2019 Tesla Model S

9.3.2 define attributes and methods for subclasses

class ElectricCar(Car):
    """The uniqueness of electric vehicles."""

    def __init__(self, make, model, year):
        """Initializes the properties of the parent class."""
        super().__init__(make, model, year)
        self.battery_size = 75

    def describe_battery(self):
        """Print 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()
2019 Tesla Model S
This car has a 75-kWh battery.

9.3.3 method of overriding parent class

    def fill_gas_tank(self):
        """Electric cars have no fuel tanks."""
        print("This car doesn't need a gas tank!")

9.3.4 using instances as attributes

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

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

    def update_odometer(self, mileage):
        """
        Set the odometer reading to the specified value.
        It is forbidden to callback 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):
        """Increase the odometer reading by the specified amount."""
        self.odometer_reading += miles


class Battery:
    """A simple attempt to simulate electric vehicle battery."""

    def __init__(self, battery_size=75):
        """Initialize battery properties."""
        self.battery_size = battery_size

    def describe_battery(self):
        """Print a message describing the battery capacity."""
        print(f"This car has a {self.battery_size}-kWh battery.")


class ElectricCar(Car):
    """The uniqueness of electric vehicles."""

    def __init__(self, make, model, year):
        """Initializes the properties of the parent class."""
        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()
2019 Tesla Model S
This car has a 75-kWh battery.
class Battery:
    """A simple attempt to simulate electric vehicle battery."""

    def __init__(self, battery_size=75):
        """Initialize battery properties."""
        self.battery_size = battery_size

    def describe_battery(self):
        """Print a message describing the battery capacity."""
        print(f"This car has a {self.battery_size}-kWh battery.")

    def get_range(self):
        """Print a message indicating the battery range."""
        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.")
2019 Tesla Model S
This car has a 75-kWh battery.
This car can go about 260 miles on a full charge.

9.3.5 simulated object

There is no right or wrong in the modeling methods of the real world. Some methods are more efficient, but it needs some practice to find the most efficient representation.

9.4 import class

9.4.1 importing a single class

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()
2019 Audi A4
This car has 23 miles on it.

9.4.2 storing multiple classes in one module

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()
2019 Tesla Model S
This car has a 75-kWh battery.
This car can go about 260 miles on a full charge.

9.4.3 importing multiple classes from a module

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())
2019 Volkswagen Beetle
2019 Tesla Roadster

9.4.4 import the whole module

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())
2019 Volkswagen Beetle
2019 Tesla Roadster

9.4.5 import all classes in the module

from module_name import *

9.4.6 importing one module into another

from car import Car
from electric_car import 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())
2019 Volkswagen Beetle
2019 Tesla Roadster

9.4.7 using aliases

from car import Car
from electric_car import ElectricCar as EC

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

my_tesla = EC('tesla', 'roadster', 2019)
print(my_tesla.get_descriptive_name())
2019 Volkswagen Beetle
2019 Tesla Roadster

9.4.8 custom workflow

Start by making the code structure as simple as possible. Make sure that all the work can be completed in a separate class as soon as possible.

9.5 Python standard library

The Python standard library is a set of modules, which are included in the Python we install.

from random import randint

print(randint(1, 6))
4
from random import choice
players = ['charles', 'martina', 'michael', 'florence', 'eli']
first_up = choice(players)
print(first_up)
florence

Class 9.6 coding style

The class name shall adopt hump naming method, that is, the first letter of each word in the class name shall be capitalized without underline. The instance name and module name are in lowercase and underlined between words.

Tags: Python

Posted by spirp on Mon, 18 Apr 2022 17:26:43 +0930