《python编程:从入门到实践》查漏补缺(2)函数, 类, 文件和异常

函数, 类, 文件和异常:
#coding=gbk
#Python编程:从入门到实践
#第8章:函数
#形参是函数定义的,实参是用户自己输入的具体参数
#让实参变成是可选的
def get_name(first_name,last_name,middle_name=''):
    if middle_name:
        full_name=first_name + ' ' + middle_name + " " + last_name
    else:
        full_name= first_name + ' ' + last_name 
    return full_name
name1=get_name('张','san')
name2 = get_name('尼古拉斯','si','赵')
print(name1)
print(name2)   
#  张 san
# 尼古拉斯 赵 si

#使用字典使实参变成可选的
def person(first_name, last_name, age=''):
    p={'first':first_name, 'last':last_name}
    if age:
        p['age']=age
    return p
p=person('liu ','dehua',37)
print(p)        #{'last': 'dehua', 'age': 37, 'first': 'liu '}


#第9章:类
#类的编码风格
#类名中的每个单词的首字母都要大写, 不是有下划线 _ 分割
#实例名和模块名 都要 采用 小写格式 ,在单词之间使用下划线分开
#car类
class Car():
    def __init__(self,make,model , year):   #构造函数
        self.make = make
        self.model= model
        self. year = year
    def get_message(self):
        message = str(self.year) + ' ' + self.make + " " + self.model   #定义方法
        return message
my_car = Car('audi','a8',2018)
print(my_car.get_message())     #  2018 audi a8

#通过方法来修改属性的值
class Car1():
    def __init__(self, make, model, year ):
        self.make = make 
        self.model = model 
        self.year = year
        self.miles = 100 
    def updat_miles(self,new_miles):
        if self.miles > new_miles :
            print('输入错误')
        else: 
            self.miles = new_miles
    def read_miles(self):
        print('The car has ' + str(self.miles) + ' miles on it')
my_car1 = Car1('audi','a8',2018)
my_car1.updat_miles(120)
my_car1.read_miles()    # The car has 100 miles on it

#将实例用作属性
class Car2():
    def __init__(self,make,model , year):   #构造函数
        self.make = make
        self.model= model
        self. year = year
    def get_message(self):
        message = str(self.year) + ' ' + self.make + " " + self.model   #定义方法
        return message
class Battery():
    def __init__(self, battery_size  = 100):
        self.battery_size = battery_size 
    def read_battery_size(self):
        print('This car has '+ str(self.battery_size) +' -kwh battery')
class ElectricCar(Car2):
    def __init__(self, make , model, year ):
        Car2.__init__(self, make, model, year)
        self.battery = Battery()
my_tesla = ElectricCar('Tesla ', 'model s',2018)    #2018 Tesla  model s
print(my_tesla.get_message())
my_tesla.battery.read_battery_size()    # This car has 100 -kwh battery

# car 和 my_car 代表模块 ,对应为 car.py  和 my_car.py       
#导入单个类,如果Car 类存放在 car.py 这个模块中
#可以新建一个模块my_car.py ,使用 from car import Car 来使用这个Car 类
#可以在其中导入Car 类 并创建其对应的实例
#也可以使用 from car import Car , ElectricCar , 来导入多个类
#导入整个模块 - import car
#导入模块中的所有的类 —— from car impor * 


#文件和异常
#逐行读取
file_name = r'C:\Users\Administrator\Desktop\mysal\Python\data.txt'
with open(file_name) as file:
    for line in file:
        print(line.rstrip())    #.rstrip() 去除多余的空白行 ,删除r 右边的空格
# hello
# this
# world

#创建一个包含文件各行的内容的列表
file_name = r'C:\Users\Administrator\Desktop\mysal\Python\data.txt'
with open(file_name) as file:
    lines = file.readlines()
for line in lines:
    print(line.rstrip())

#使用文件中的内容    
file_name = r'C:\Users\Administrator\Desktop\mysal\Python\data.txt'
with open(file_name) as file:
    lines = file.readlines()
print_hello = ''
for line in lines:
    print_hello += line.strip() + ' '   #输出 hello this world
print(print_hello)
 
       
#异常
print('Give me two numberr , and i will divide them ') 
print(' Enter q to quit ')
while True:
    first_number = input ('\n First number:')
    if first_number == 'q':
        break
    second_number = input('\n Second  number:')
    if second_number == 'q' :
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print('分母不能为0')
    else:
        print('The result is  ' + str(answer))
        break
#  First number:12            将只有可能引发异常的 代码放入 try 语句中,
#                            else中的代码只有在try的语句中成功执行才能执行
#  Second  number:0        excep 中语句抛出异常,打印一条友善的语句, 用户不需要看到   traceback 
# 分母不能为0    


#存储数据
import json
numbers = [1,2,4,6,8,9]
file_name = r'C:\Users\Administrator\Desktop\mysal\Python\number.json'
with open(file_name,'w') as file:
    json.dump(numbers, file)   # 将numbers 数据存储到文件中, json格式
 
#加载json 格式数据
file_name = r'C:\Users\Administrator\Desktop\mysal\Python\number.json'
with open(file_name) as file:
    number1 = json.load(file)
print(number1)          #[1, 2, 4, 6, 8, 9]
 


猜你喜欢

转载自blog.csdn.net/qq_40587575/article/details/80820315