Post

Python Crash Course 9 - Class

I’m YouKoutaku. These codes are from the book python_Crash_Course, 2nd edition. I learned python and took these notes for this book.

9. Class

9.1 create and use class

9.1.1 create a class

class_name must be capital.

1
2
3
4
5
6
7
8
9
10
11
12
class Dog:
    """dog class"""
    def __init__(self, name, age):
        """setup for name and age"""
        self.name = name
        self.age = age
    def sit(self):
        """dog sit"""
        print(f"{self.name} is now sitting.")
    def roll_over(self):
        """"""
        print(f"{self.name} rolled over!")

The function in class is called method.

_init_(self, parameter_name, ...)

The self must be the frist argument. self can used by all methods in class. another parameter. self.parameter_name is called properties.

9.1.2 create a instance

  1. using the properties of class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Dog:
    """dog class"""
    def __init__(self, name, age):
        """setup for name and age"""
        self.name = name
        self.age = age
    def sit(self):
        """dog sit"""
        print(f"{self.name} is now sitting.")
    def roll_over(self):
        """"""
        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.")
1
2
My dog's name is Willie.
My dog is 6 years old.
  1. using the methods of class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Dog:
    """dog class"""
    def __init__(self, name, age):
        """setup for name and age"""
        self.name = name
        self.age = age
    def sit(self):
        """dog sit"""
        print(f"{self.name} is now sitting.")
    def roll_over(self):
        """"""
        print(f"{self.name} rolled over!")

my_dog = Dog('Willie', 6)

my_dog.sit()
my_dog.roll_over()
1
2
Willie is now sitting.
Willie rolled over!
  1. more instance used class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog:
    """dog class"""
    def __init__(self, name, age):
        """setup for name and age"""
        self.name = name
        self.age = age
    def sit(self):
        """dog sit"""
        print(f"{self.name} is now sitting.")
    def roll_over(self):
        """"""
        print(f"{self.name} rolled over!")

my_dog = Dog('Willie', 6)
your_dog = Dog('Lucy',3)

my_dog.sit()
your_dog.roll_over()
1
2
Willie is now sitting.
Lucy rolled over!

9.2 using class and instance

9.2.1 a sample class

1
2
3
4
5
6
7
8
9
10
11
12
13
class Car:
    """simulation for car"""
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
    def get_descriptive_name(self):
        """return info"""
        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())
1
2019 Audi A4

9.2.2 default values for properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    def read_odometer(self):
        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()
1
2
2019 Audi A4
This car has 0 miles on it.

9.2.3. change values of properties

  1. Directly
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    def read_odometer(self):
        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()
1
2
2019 Audi A4
This car has 23 miles on it.
  1. by method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    def read_odometer(self):
        print(f"This car has {self.odometer_reading} miles on it.")
    def update_odometer(self, mileage):
        """change the odometer 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()
1
2
2019 Audi A4
This car has 23 miles on it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#app extra work
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    def read_odometer(self):
        print(f"This car has {self.odometer_reading} miles on it.")
    def update_odometer(self, mileage):
        """change the odometer value and """
        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()

my_new_car.update_odometer(13)
my_new_car.read_odometer()
1
2
3
4
2019 Audi A4
This car has 23 miles on it.
You can't roll back an odometer!
This car has 23 miles on it.
  1. increment the value by method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    def read_odometer(self):
        print(f"This car has {self.odometer_reading} miles on it.")
    def update_odometer(self, mileage):
        """change the odometer value and """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        """increment the value to odometer"""
        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(1000)
my_new_car.read_odometer()

1
2
3
2019 Audi A4
This car has 23500 miles on it.
This car has 24500 miles on it.

9.3 Inheritance

child class can get all methods and properties of parent class.

class child_class_name (parent_class)

9.3.1 _init_() in child class

usually, _init_() of the child clsss need info from _init_() of the parent clsss

super()._init_(parameter_name, ...) is a method to define all properties and methods from parent class. The parent class also is called supercalss, so uesd super.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    def read_odometer(self):
        print(f"This car has {self.odometer_reading} miles on it.")
    def update_odometer(self, mileage):
        """change the odometer value and """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        """increment the value to odometer"""
        self.odometer_reading += miles
        
class ElectricCar(Car):
    def __init__(self, make, model, year):
        """add parent class's properties and methods"""
        super().__init__(make, model, year)

my_new_car = ElectricCar('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
1
2019 Audi A4

9.3.2 add the properties and methods for child class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
    def read_odometer(self):
        print(f"This car has {self.odometer_reading} miles on it.")
    def update_odometer(self, mileage):
        """change the odometer value and """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        """increment the value to odometer"""
        self.odometer_reading += miles
        
class ElectricCar(Car):
    def __init__(self, make, model, year):
        """add parent class's properties and methods"""
        super().__init__(make, model, year)
        self.battery_size = 75
    def describe_battery(self):
        """print the battery info"""
        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()

1
2
2019 Tesla Model S
This car has a 75-kWh batery.

9.3.3 Rewriting the methoed of parent class

define the same name method again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Car:
    """simulation for car"""
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def fill_gas_tank(self):
        print("xxxxxx")

class ElectricCar(Car):
    def __init__(self, make, model, year):
        """add parent class's properties and methods"""
        super().__init__(make, model, year)
        self.battery_size = 75
    def fill_gas_tank(self):
        print("This car doesn't need a gas tank!")

my_tesla = ElectricCar('tesla', 'model s', 2019)
my_tesla.fill_gas_tank()
1
This car doesn't need a gas tank!

9.3.4 make instence as a properties

The list of properties and methods is longer when the class has more detals. So we can create a sub-instence by class as properties of the main-isntence in _init_().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
class Battery:
    def __init__(self, battery_size=75):
        self.battery_size = battery_size
    def describe_battery(self):
        """print the battery info"""
        print(f"This car has a {self.battery_size}-kWh battery.")
class ElectricCar(Car):
    def __init__(self, make, model, year):
        """add parent class's properties and methods"""
        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()
1
2
2019 Tesla Model S
This car has a 75-kWh batery.

It seems unnecessary, but this grading method can help us better understand and modify our code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Car:
    """simulation for 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):
        """return info"""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()
class Battery:
    def __init__(self, battery_size=75):
        self.battery_size = battery_size
    def describe_battery(self):
        """print the battery info"""
        print(f"This car has a {self.battery_size}-kWh battery.")
    def get_range(self):
        if self.battery_size == 75:
            range = 260
        if self.battery_size == 100:
            range = 315
        print(f"This car can go about {range} miles on a full charge.")
class ElectricCar(Car):
    def __init__(self, make, model, year):
        """add parent class's properties and methods"""
        super().__init__(make, model, year)
        self.battery = Battery()

my_car = ElectricCar('tesla', 'model s', 2019)
print(my_car.get_descriptive_name())
my_car.battery.describe_battery()
my_car.battery.get_range()
1
2
3
2019 Tesla Model S
This car has a 75-kWh batery.
This car can go about 260 miles on a full charge.

9.4 import class

9.4.1 import a single class

from file_name import class_name

1
2
3
4
5
6
7
8
9
10
from car import Car

my_car = Car('tesla', 'model s', 2019)
print(my_car.get_descriptive_name())

my_car.update_odometer(23_500)
my_car.read_odometer()

my_car.increment_odometer(1000)
my_car.read_odometer()

9.4.2 multiple classes in one module

1
2
3
4
5
6
from car import ElectricCar

my_car = ElectricCar('tesla', 'model s', 2019)
print(my_car.get_descriptive_name())
my_car.battery.describe_battery()
my_car.battery.get_range()

9.4.3 import multiple classes

from file_name import class_name, class_name, xxxx

1
2
3
4
5
6
7
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())

9.4.4 import one modules

import module_name

1
2
3
4
5
6
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())

9.4.5 import all classes in one module

from module_name import *

But this way is not a good. because we can’t know where the class from. And class’s name maybe repeated.

9.4.6 import one module to another module

1
2
3
4
5
6
7
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())

9.4.7 rename a class when importing

from module_name import class_name as new_name

9.5 python standard library

1
2
3
from random import randint

randint(1, 100)
1
61
1
2
3
4
from random import choice
players = ['charles', 'martina', 'michael', 'david']
first_up = choice(players)
print(first_up)
1
charles
This post is licensed under CC BY 4.0 by the author.