Python学习笔记(五)

1.根据约定,首字母大写的名称指的是类。

2.类中的函数称为方法。

3.将实例用作属性的例子:

class User():
    def __init__(self,name):
        self.name = name
        self.color = 'red'

    def describe_user(self):
        print(f"Hello! My name is {self.name}")
    
class Privileges():
    def __init__(self):
        self.privileges = ['can add post','can delete post','can ban user']
    def show_pribileges(self):
        print(self.privileges)

class Admin(User):
    def __init__(self, name):
        super().__init__(name)
        self.privilege = Privileges()
    
fx = Admin('fx')
fx.privilege.show_pribileges()

4.电动车电瓶升级案例:

class 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):
        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):
        if mileage >= self.odometer_reading:
            self.odometer_reading += mileage
        else:
            print("You can't do that!")
    
    def increment_odometer(self, miles):
        self.odometer_reading += miles

class Battery:
    def __init__(self, battery_size =75):
        self.battery_size = battery_size

    def describe_battery(self):
        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.")

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

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

car_test = ElectricCar('tesla', 'model s', 2019)
car_test.battery.get_range()
car_test.battery.upgrade_battery()
car_test.battery.get_range()
    

5.到导入模块中的每个类时,最好不要用:

from module_name import *

需要从一个模块中导入很多类的时候,最好导入整个模块,并使用module_name.Classname语法来访问类。

6.将两个整数作为参数,并随机返回一个位于这两个整数之间的整数:

random.randint()

7.将一个列表或者元组作为参数,并随即返回其中一个元素:

random.choice()

8.类名应该采用驼峰命名法,即将类名中的每个单词的首字母都大写,而不是用下划线。实例名和模块名称都采用小写格式,并在单词之间加上下划线。

9.在类中,可用一个空行来分割方法;在模块中,可用两个空行分割类

上一篇:Python类学习4


下一篇:Magic Battery for mac(连接设备电量显示)