Python programming: Getting Started to Practice Chapter 9

9-1 Restaurant: Create a class named Restaurant whose method __init__() sets two properties: Restaurant_name and Cuisine_type. Create a method called describe_restaurant(), which prints both information, and a method called open_restaurant(), which prints a message indicating that the restaurant is open.

class Restaurant() :
    def __init__(self, restaurant_name, cuisine_type) :
        self.r_name = restaurant_name
        self.c_type = cuisine_type
        
    def describe_restaurant(self) :
        print("\nRestaurant's name is:", self.r_name.title(),
              "and it has", self.c_type.title()+".")
        
    def open_restaurant(self) :
        print('\n' + self.r_name.upper(), 'is opening! ')

dinner = Restaurant('kfc'.'chips')

Restaurant.describe_restaurant(dinner)
Restaurant.open_restaurant(dinner)
Copy the code

Output result:

Restaurant's name is: Kfc and it has Chips.

KFC is opening!
Copy the code

Create an instance of this class called restaurant, print its two properties, and call the two methods.

See above.

9-2 Three restaurants: Create three instances of the classes you wrote to complete Exercise 9-1 and call the method describe_restaurant() on each instance.

A little.

9-3 User: Create a class named User that contains the attributes first_name and last_name, as well as several other attributes that the User profile would normally store. Define a method called describe_user() in the User class that prints a summary of User information. Define a method called greet_user() that sends a personalized greeting to the user.

Create multiple instances representing different users and call the above two methods on each instance.

class User() :
    def __init__(self, first_name, last_name, gender='male') :
        self.f_name = first_name
        self.l_name = last_name
        self.g_gender = gender
    
    def describe_user(self) :
        print(self.f_name.title(), self.l_name.title(), 
              'has the following details:',self.g_gender +'. ')
    
    def greet_user(self) :
        print('Hello,', self.f_name, self.l_name + '.\n')

a = User('san'.'zhang')
User.describe_user(a)
User.greet_user(a)

b = User('si'.'li'.'female')
User.describe_user(b)
User.greet_user(b)
Copy the code

Output result:

San Zhang has the following details: male.
Hello, san zhang.

Si Li has the following details: female.
Hello, si li.
Copy the code

9-4 Number of people served: In the program you wrote to complete Exercise 9-1, add a property called number_served and set its default value to 0. Create an instance named restaurant from this class; Print how many people have eaten at the restaurant, then modify the value and print it again.

Add a method called set_number_served() that lets you set the number of people served. Call this method and pass it a value, then print the value again.

Add a method called increment_number_served() that lets you increase the number of people served. Call this method and pass it a value of how many people you think the restaurant is likely to serve each day.

class Restaurant() :
    def __init__(self, restaurant_name, cuisine_type, number_served=0) :
        self.r_name = restaurant_name
        self.c_type = cuisine_type
        self.no_served = number_served
        
    def describe_restaurant(self) :
        print("Restaurant's name is:", self.r_name.title(),
              "and it has", self.c_type.title(), "and served", self.no_served,
              'people.\n')
        
    def open_restaurant(self) :
        print(self.r_name.upper(), 'is opening! \n')
        
    def set_number_served(self, number_served) :
        self.no_served = number_served
        
    def increment_number_served(self, incre_number) :
        self.no_served += incre_number
        

print('-----Original:------')
dinner = Restaurant('kfc'.'chips')
Restaurant.describe_restaurant(dinner)

print('-----Fixed served number-----')
dinner = Restaurant('burger king'.'coke'.23)
Restaurant.describe_restaurant(dinner)

print('-----Revised served-----')
dinner = Restaurant('mcdonald'.'burgers'.23)
dinner.set_number_served(54)
Restaurant.describe_restaurant(dinner)

print('-----Incremental served-----')
dinner = Restaurant('pizza hut'.'pizza'.23)
dinner.set_number_served(100)
dinner.increment_number_served(20)
Restaurant.describe_restaurant(dinner)
Copy the code

Results:

-----Original:------
Restaurant's name is: Kfc and it has Chips and served 0 people.

-----Fixed served number-----
Restaurant's name is: Burger King and it has Coke and served 23 people.

-----Revised served-----
Restaurant's name is: Mcdonald and it has Burgers and served 54 people.

-----Incremental served-----
Restaurant's name is: Pizza Hut and it has Pizza and served 120 people.
Copy the code

9-5 Number of login attempts: In the User class written to complete Exercise 9-3, add a property called login_Attempts. Write a method called increment_login_attempts() that increments the value of the attribute login_Attempts by one. Write a method called reset_login_attempts(), which resets the value of the attribute login_attempts to 0.

Create an instance from the User class and call the method increment_login_attempts() several times. Prints the value of the attribute login_attempts to verify that it has been properly incremented; The method reset_login_attempts() is then called and the value of the attribute login_Attempts is printed again to confirm that it has been reset to 0.

class User() :
    def __init__(self, first_name, last_name, gender='male') :
        self.f_name = first_name
        self.l_name = last_name
        self.g_gender = gender
        self.loggin_attempt = 0
    
    def describe_user(self) :
        print(self.f_name.title(), self.l_name.title(), 
              'has the following details:',self.g_gender +'. ')
    
    def greet_user(self) :
        print('Hello,', self.f_name, self.l_name + '.\n')
        
    def increment_login_attempts(self) :
        self.loggin_attempt += 1
        print('He attempted', self.loggin_attempt, 'logins.')
        
    def reset_login_attempts(self) :
        self.loggin_attempt = 0
        print(self.loggin_attempt)

a = User('san'.'zhang')
a.describe_user()
a.greet_user()

n = 0
while n<5:
    n += 1
    a.increment_login_attempts()

a.reset_login_attempts()
Copy the code

Results:

San Zhang has the following details: male.
Hello, san zhang.

He attempted 1 logins.
He attempted 2 logins.
He attempted 3 logins.
He attempted 4 logins.
He attempted 5 logins.
0
Copy the code

9-6 Ice Cream Parlor: An ice cream parlor is a special kind of restaurant. Write a class called IceCreamStand that inherits the Restaurant class you wrote to complete exercise 9-1 or exercise 9-4. Either version of the Restaurant class works, so just pick the one you like better. Add a flavors property that stores a list of ice cream flavors. Write a method to display the ice cream. Create an IceCreamStand instance and call this method.

class Restaurant() :
    def __init__(self, restaurant_name, cuisine_type, number_served=0) :
        self.r_name = restaurant_name
        self.c_type = cuisine_type
        self.no_served = number_served
        
    def describe_restaurant(self) :
        print("Restaurant's name is:", self.r_name.title(),
              "and it has", self.c_type.title(), "and served", self.no_served,
              'people.\n')
        
    def open_restaurant(self) :
        print(self.r_name.upper(), 'is opening! \n')
        
    def set_number_served(self, number_served) :
        self.no_served = number_served
        
    def increment_number_served(self, incre_number) :
        self.no_served += incre_number
        

class IceCreamstand(Restaurant) :
    def __init__(self, restaurant_name, cuisine_type) :
        super().__init__(restaurant_name,cuisine_type)
        self.flavor_list = []   
        
    def flavors(self) :
        for flavor in self.flavor_list:
            print('Ice cream tastes are:', flavor + '. ')
          

        
print('-----Original:------')
dinner = Restaurant('kfc'.'chips')
dinner.describe_restaurant()

print('-----Fixed served number-----')
dinner = Restaurant('burger king'.'coke'.23)
dinner.describe_restaurant()

print('-----Revised served-----')
dinner = Restaurant('mcdonald'.'burgers'.23)
dinner.set_number_served(54)
dinner.describe_restaurant()

print('-----Incremental served-----')
dinner = Restaurant('pizza hut'.'pizza'.23)
dinner.set_number_served(100)
dinner.increment_number_served(20)
dinner.describe_restaurant()

print('-----Ice cream flavor-----')
taste = IceCreamstand('DQ'.'Ice Shake')

flavor_list = []
while True:
    flavor_input = input("name a flavor, press q to quit:\n\t")
    ifflavor_input ! ='q':
        flavor_list.append(flavor_input)
    else:
        break
taste.flavor_list = flavor_list
taste.flavors()
Copy the code

Practice while. Results:

-----Original:------
Restaurant's name is: Kfc and it has Chips and served 0 people.

-----Fixed served number-----
Restaurant's name is: Burger King and it has Coke and served 23 people.

-----Revised served-----
Restaurant's name is: Mcdonald and it has Burgers and served 54 people.

-----Incremental served-----
Restaurant's name is: Pizza Hut and it has Pizza and served 120 people.

-----Ice cream flavor-----

name a flavor, press q to quit:
	berry

name a flavor, press q to quit:
	vanilla

name a flavor, press q to quit:
	chocolate

name a flavor, press q to quit:
	moccha

name a flavor, press q to quit:
	q
Ice cream tastes are: berry.
Ice cream tastes are: vanilla.
Ice cream tastes are: chocolate.
Ice cream tastes are: moccha.

Copy the code

9-7 Administrator: An administrator is a special user. Write a class named Admin that inherits the User class you wrote for exercise 9-3 or exercise 9-5. Add a property named PRIVILEGES that stores a list of strings such as “can add POST “, “Can delete POST”, “Can ban user”, etc. Write a method called show_PRIVILEGES () that shows the privileges of the administrator. Create an Admin instance and call this method.

class User() :
    def __init__(self, first_name, last_name, other_info=' ') :
        self.f_name = first_name
        self.l_name = last_name
        self.o_info = other_info
        self.login_attempts = 0
        
    def describe_user(self) :
        if self.o_info:
            print('User', self.l_name.title(), self.f_name.title(),
                  'has following info:', self.o_info)
        else:
            print('User', self.l_name.title(), self.f_name.title() + '. ')

    def greet_user(self) :
        print('Hello,', self.l_name.title(), self.f_name.title()+'. ')

    def increment_login_attempts(self) :
        for x in range(0.4.1):  
            self.login_attempts += 1
            print('Logging attempts:', self.login_attempts)
    
    def reset_login_attempts(self) :
        self.login_attempts = 0
        print('Reset loging:', self.login_attempts)

class Admin(User) :
    def __init__(self, first_name, last_name) :
        super().__init__(first_name, last_name)
        self.privileges = ["can add post" ,"can delete post" ,"can ban user"]
        
    def show_privileges(self) :
        for x in self.privileges:
            print("Admin's privileges include",x +'. ')

p1 = User('san'.'zhang'.23)
p1.describe_user()
p1.greet_user()
p1.increment_login_attempts()
p1.reset_login_attempts()

p2= Admin('si'.'li')
p2.show_privileges()
Copy the code

Results:

User Zhang San has following info: 23
Hello, Zhang San.
Logging attempts: 1
Logging attempts: 2
Logging attempts: 3
Logging attempts: 4
Reset loging: 0
Admin's privileges include can add post.
Admin's privileges include can delete post.
Admin's privileges include can ban user.
Copy the code

9-8 Privileges: Write a class named Privileges that has only one property, Privileges, and stores the list of strings described in Exercise 9-7. Move the method show_PRIVILEGES () into this class. In the Admin class, use a Privileges instance as its property. Create an Admin instance and use the method show_PRIVILEGES () to show its privileges.

class User() :
    def __init__(self, first_name, last_name, other_info=' ') :
        self.f_name = first_name
        self.l_name = last_name
        self.o_info = other_info
        self.login_attempts = 0
        
    def describe_user(self) :
        if self.o_info:
            print('User', self.l_name.title(), self.f_name.title(),
                  'has following info:', self.o_info)
        else:
            print('User', self.l_name.title(), self.f_name.title() + '. ')

    def greet_user(self) :
        print('Hello,', self.l_name.title(), self.f_name.title()+'. ')

    def increment_login_attempts(self) :
        for x in range(0.4.1):  
            self.login_attempts += 1
            print('Logging attempts:', self.login_attempts)
    
    def reset_login_attempts(self) :
        self.login_attempts = 0
        print('Reset loging:', self.login_attempts)

class Admin(User) :
    def __init__(self, first_name, last_name) :
        super().__init__(first_name, last_name)
        self.priv = Privileges()
            
class Privileges() :
    def __init__(self, privileges=[]) :
        self.priv = privileges

    def show_privileges(self) :
        if self.priv:
            for x in self.priv:
                print("Admin's privileges in Class Previleges include",x +'. ')
        else:
                print('There is no privilege.')


person = Admin('wu'.'wang')
person.priv.show_privileges()  # display no privilege

my_privileges = ['can reset passwords'.'can moderate discussions'.'can suspend accounts']

person.priv.priv = my_privileges 
# Why twice? Passed once to Admin (User) and again to Privileges?

person.priv.show_privileges() # privilege is displayed
Copy the code

Results:

There is no privilege.
Admin's privileges in Class Previleges include can reset passwords.
Admin's privileges in Class Previleges include can moderate discussions.
Admin's privileges in Class Previleges include can suspend accounts.
Copy the code

Person. Priv. Priv = my_PRIVILEGES stuck for a long time. I couldn’t pass in the list at first.

9-9 Battery upgrade: In the last electric_car.py version of this section, add a method called upgrade_battery() to the Battery class. This method checks the battery capacity and if it is not 85, sets it to 85. To create an electric car with the default battery capacity, call the method get_range(), then upgrade the battery and call get_range() again. You will see an increase in the range of this car.

class Car() :
    """A simple attempt to represent a car."""

    def __init__(self, manufacturer, model, year) :
        """Initialize attributes to describe a car."""
        self.manufacturer = manufacturer
        self.model = model
        self.year = year
        self.odometer_reading = 0
        
    def get_descriptive_name(self) :
        """Return a neatly formatted descriptive name."""
        long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model
        return long_name.title()
    
    def read_odometer(self) :
        """Print a statement showing the car's mileage."""
        print("This car has " + str(self.odometer_reading) + " miles on it.")
        
    def update_odometer(self, mileage) :
        """ Set the odometer reading to the given value. Reject the change if it attempts to roll 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) :
        """Add the given amount to the odometer reading."""
        self.odometer_reading += miles

class Battery() :
    """A simple attempt to model a battery for an electric car."""

    def __init__(self, battery_size=60) :
        """Initialize the batteery's attributes."""
        self.battery_size = battery_size

    def describe_battery(self) :
        """Print a statement describing the battery size."""
        print("This car has a " + str(self.battery_size) + "-kWh battery.")

        
    def get_range(self) :
        """Print a statement about the range this battery provides."""
        if self.battery_size == 60:
            range = 140
        elif self.battery_size == 85:
            range = 185
            
        message = "This car can go approximately " + str(range)
        message += " miles on a full charge."
        print(message)

    def upgrade_battery(self) :
        ifself.battery_size ! =85:
            self.battery_size = 85
            print('Battery upgraded to 85.')
        else:
            print("You don't need upgrade.")
        
class ElectricCar(Car) :
    """Models aspects of a car, specific to electric vehicles."""

    def __init__(self, manufacturer, model, year) :
        """ Initialize attributes of the parent class. Then initialize attributes specific to an electric car. """
        super().__init__(manufacturer, model, year)
        self.battery = Battery()
        

my_car = ElectricCar('Honda'.'Accord'.'2019')
print('Prior to upgrading:')
my_car.battery.get_range()

print('\nUpgrade battery:')
my_car.battery.upgrade_battery()

print('\nRange check after upgrading:')
my_car.battery.get_range()
Copy the code

This section of the textbook above the code copied… I’m too lazy to type in… Results:

Prior to upgrading:
This car can go approximately 140 miles on a full charge.

Upgrade battery:
Battery upgraded to 85.

Range check after upgrading:
This car can go approximately 185 miles on a full charge.
Copy the code

9-10 Import Restaurant class: Store the latest Restaurant class in a module. In a separate file, import the Restaurant class, create an instance of Restaurant, and call a method of Restaurant to verify that the import statement is correct.

from rest import Restaurant

Copy the code

9-11 Importing the Admin class: Based on the work done in exercise 9-8, store the User, Privileges, and Admin classes in a module, create a file, create an instance of Admin in it and call the method show_PRIVILEGES () on it to verify that everything works correctly.

from priv import User, Privileges, Admin
Copy the code

9-12 Multiple modules: Store the User class in one module and the Privileges and Admin classes in another module. Create another file, create an instance of Admin in it, and call the method show_PRIVILEGES () on it to verify that everything is still working correctly.

from a import User
from b import Privileges, Admin
Copy the code

9-13 Using OrderedDict: In Exercise 6-4, you used a standard dictionary to represent the vocabulary. Rewrite the program using the OrderedDict class and make sure the output is in the same order as you added key-value pairs to the dictionary.

from collections import OrderedDict
names = OrderedDict()
names = {'string':'String'.'list':'list'.'tuple':'a tuple,}for key, value in names.items():
    print('\t'+key,'is:',value)

names['print'] = 'print'
names['import'] = 'import'

for key, value in names.items():
    print('\t'+key,'is:',value)

Copy the code

Dice 9-14: The module random contains functions for generating random numbers in various ways, where randint() returns an integer in the specified range. For example, the following code returns an integer between 1 and 6:

from random import randint 
x = randint(1.6) 
Copy the code

Create a Die class that contains a property called sides, with a default value of 6. Write a method called roll_die() that prints a random number between 1 and the number of die faces. Create a six-sided die and roll it 10 more times. Create a 10-sided die and a 20-sided die and roll them both 10 times.

from random import randint

class Die() :

    def __init__(self, dice_side) :
        self.sides = dice_side
     
    def roll_die(self) :
        return randint(1, self.sides)

roll_results = []

num = input('How many rolls? ')

d = Die(int(num)) 
   
for x in range(int(num)):
    result = d.roll_die()
    roll_results.append(result)
    
print('Results are:',roll_results)
Copy the code

Modified to roll any number. Results:

How many rolls? 15 Results are: [2, 13, 1, 11, 12, 9, 2, 3, 14, 9, 3, 5, 2, 8, 9]Copy the code

9-15 PythonModule ofthe Week: A great resource to learn about the Python standard library is the website PythonModule ofthe Week. Go to Pymotw.com/ and check out the table of contents, find a module that interests you to explore, or read the documentation for the collections and Random modules.

I went to the cinema with my family the day before yesterday. So I just reviewed it. However, the review harvest is still a lot of ah.