九、类8-习题2-end(2022-04-25)

9-5.为9-3编写的user类添加一个名为login_attempts的属性,编写一个名为increment_login_attempts()的方法,将属性login_attempts的值加1.

编写一个reset_login_attempts()方法, 将login_attmepts重置为0.

class User2:
    def __init__(self, frist_name, last_name, age, login_attempts, **kwargs):
        self.frist_name = frist_name
        self.last_name = last_name
        self.age = age
        self.login_attempts = login_attempts
        self.dict = {}
        for k, v in kwargs.items():
            setattr(self, k, v)  # setattr(x,y,z)的作用是,将x的属性y赋值z (x.y = z),即 self.k = v 初始化属性并赋值。
            self.dict[k] = v
        # print(self.dict)

    def full_name(self):
        full_name = f"{self.last_name} {self.frist_name}".title()
        return full_name

    def describe_user(self):
        print(f"The user-{self.full_name()} is {self.age} years old.")
        print(f"{self.full_name()}'s other information:"
              f"\n\t{self.dict}")

    def greet_user(self):
        print(f"Hello , {self.full_name()} !")

    def increament_login_attemps(self, increament_attemps):
        self.login_attempts += increament_attemps

    def reset_login_attemps(self):
        self.login_attempts = 0
        print(f"The numbr of login attempts reset to {self.login_attempts}.")


user_wang = User2('xihe','wang',7,0)
user_wang.describe_user()
user_wang.increament_login_attemps(4)
print(f"The user's login attemps number is {user_wang.login_attempts} .")
user_wang.reset_login_attemps()

The user-Wang Xihe is 7 years old.
Wang Xihe's other information:
{}
The user's login attemps number is 4 .
The numbr of login attempts reset to 0.

9-6 编写一个名为IceCreamStandRestaurant的类,继承9-1或9-4编写的restaurant类,添加一个flavors属性,用于存储一个由各种冰淇凌组成的列表。

编写一个显示这些列表的方法,创建一个类的实例,并调用这个方法。

class IceCreamStandResraurant(Restaurant):
    def __init__(self,restaurant_name,cuisine_type,flavors):  #初始化属性时,可以直接增加属性。本例增加了flavors属性
        super().__init__(restaurant_name,cuisine_type) #注意:初始化父类的属性时,不可传入self属性,否则报错:传入参数与父类需要参数不一致。
        self.flavors = flavors #注意新增加的属性要用self.的形式进行初始化。

    def icecream_flavors(self):
        print("We serve icecream with the followding flavors:")
        for flavor in self.flavors:
            print(f"{flavor}\t",end='')


my_icecreamstand = IceCreamStandResraurant('bing dian','icecream',['strawberry','cheese','chocolate','vanilla','cream'])
my_icecreamstand.icecream_flavors()
print('')

We serve icecream with the followding flavors:
strawberry cheese chocolate vanilla cream
The user's name is Wang Yukai .
He/She is 9 years old.
Wang Yukai's other information:
{}
The admin Wang Yukai have following previleges:
Can add post Can del post Can ban user

9-8 创建一个privileges类,它只有一个属性privileges,其中存储admin的权限。将9-7的方法show_previleges移到这个类中。

在admin类中,将一个previleges实例作为其属性。创建一个admin实例,实现show_previleges()功能——显示admin的权限。

class Admin2(User):
    def __init__(self,frist_name,last_name,age,**kwargs):
        super(Admin2, self).__init__(frist_name,last_name,age,**kwargs)
        self.previleges = Previleges()


class Previleges:
    def __init__(self,previleges=['Can add post','Can del post','Can ban user']):
        self.previleges = previleges

    def show_previleges(self):
        previleges = self.previleges
        print("The admin have the following previleges :")
        for previlege in previleges:
            print(f"\t{previlege}")


admin_zhang = Admin2('xuesen','zhang',34)
admin_zhang.describe_user()
admin_zhang.previleges.show_previleges()

The user's name is Zhang Xuesen .
He/She is 34 years old.
Zhang Xuesen's other information:
{}
The admin have the following previleges :
Can add post
Can del post
Can ban user

9-9 Motor的子类为ElectricMotor,Battery类被用为ElectricMotor的属性。

给Battery类添加一个名为upgrade_battery()的方法。该方法检查电瓶,如果不是100就升级为100。

创建一个电动摩托的实例,调用get_range(),升级电瓶后,再次调用get_range(),确认是否升级成功。

class Motor:  ##首先要输入父类的代码,必须位于子类之前
    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 = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self):
        print(f"This boat has {self.odometer_reading} on it.")

    def update_odometer(self, miles):  ##使用方法修改里程
        if miles >= self.odometer_reading:  ##如果传入的里程大于原里程
            self.odometer_reading = miles  ##对里程进行修改
        else:  # 否则打印警告信息“不准回调里程表”
            print("You can't roll the odometer back.")

    def increment_odometer(self, miles):
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("You can't roll the odometer back.")


class ElectricMotor(Motor):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery = Battery()


class Battery:
    def __init__(self, battery_size=90, motor_model='electric'):
        self.battery_size = battery_size
        self.motor_model = motor_model

    def describe_battery(self):
        print(f"The Motor has a {self.battery_size}-kwh battery.")

    def get_range(self):
        """打印一条消息,指出点评的续航里程"""
        if self.battery_size > 0 and self.motor_model == 'electric':
            range = self.battery_size * 0.75
            print(f"This motor can go about {range} miles on a full charge.")
        if self.battery_size == 0 and self.motor_model != 'electric':
            range = int(input("plesas input the tank capacity:  ")) * 10
            print(f"This motor can go about {range} miles on a full tank.")

    def upgrade_battery(self):
        if self.battery_size !=100:
            self.battery_size = 100


my_electric_motor = ElectricMotor('yadi','M8',2019)
print(f"My electric motor is {my_electric_motor.get_descriptive_name()}.")
my_electric_motor.battery.get_range()
my_electric_motor.battery.upgrade_battery()
my_electric_motor.battery.get_range()

My electric motor is 2019 Yadi M8.
This motor can go about 67.5 miles on a full charge.
This motor can go about 75.0 miles on a full charge.

你可能感兴趣的:(九、类8-习题2-end(2022-04-25))