第一部分 基础知识
第8章 函数
第9章 类
from dataclasses import field
def greet_user(username):
print(f"hello, {username}")
greet_user('tom')
print('--------8.3--------')
def get_formatted_name(fname, lname, mname = ''):
if mname:
full_name = f"{fname} {mname} {lname}"
else:
full_name = f"{fname} {lname}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
print("\n======传递任意数量的实参==========\n")
def make_pizza(*toppings):
print("Make Pizza \n")
for topping in toppings:
print(topping)
print('\n')
make_pizza('pepproni')
make_pizza('mushroonm', 'green peppers', 'extra cheese')
print("\nexame2\n")
def build_profile(first, last, **user_info):
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('李', '小龙', location = '中国', field = '功夫')
print(user_profile)
print("\n-------- 8.6 -------\n")
'''
import pizza
import pizza as p
from pizza import make_pizza, f2, ....
from pizza import make_pizza s mp
from pizza import *
'''
print("\n-------------第九章 类 ----------\n")
class Dog:
"""一次模拟小狗的类"""
def __init__(self, name, age):
'''初始化属性'''
self.name = name
self.age = age
def sit(self):
print(f"{self.name} 小狗蹲下。")
def rool_over(self):
print(f"{self.name} 打滚。")
my_dog = Dog('Willie', 6)
print(f"My dog's name is : {my_dog.name}.")
print(f"My dog's age is : {my_dog.age} years old.")
my_dog.sit()
my_dog.rool_over()
print("\n---------- 9.2 Car ---------\n")
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
my_new_car = Car('audi', 'a6','2022')
print(my_new_car.get_name())
print("\n--------- 9.3 继承--------\n")
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery_size = 100
def print_battery(self):
print(f"此车的电池容量是: {self.battery_size} KWh\n")
def fill_gas_tank(self):
print("电动车没有油箱。\n")
my_tida = ElectricCar('tida', 'auto','2022')
print(my_tida.get_name())
my_tida.print_battery()
'''
class Car:
--skip--
class Battery:
--skip--
def print_battery(self)
print("-------")
clss ElectricCar(Car):
def __inin(self, make, model, year)
super().init(make, model, year)
self.battery = Battery()
my_car = ElectricCar('bmw', 'electric 400', 2022)
my_car.battery.print_battery()
'''
print("\n-------- 9.4 导入类 ---------\n")
print("\n-------- 9.5 Python标准库----- \n")
from random import randint, choice
print(randint(1,6))
players = ['aaa', 'bbb','ccc', 'ddd']
print(choice(players))
print("\n9.6 类码风格:\n类名采用驼峰命名法,即单词首字母大写。",end = ' ')
print("实例名和模块名采用小写,单词间加下划线。\n")