python基础(七)

2018-09-17  本文已影响0人  梦vctor

1、继承
1.1 子类的方法init()

class Car():
    def __init__(self,make,model,year):
        self.make=make
        self.model=model
        self.year=year
        self.odometer_reading=51
    def get_descriptive_name(self):
        long_name=str(self.year)+' '+self.make+' '+self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has "+str(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 roll back an odometer!")
    def increment_odometer(self,miles):
        self.odometer_reading+=miles
 #创建子类时,父类必须包含在当前文件中,且位于子类前面
class ElectricCar(Car):   #定义子类时,必须在括号内指定父类的名称
    def __init__(self,make,model,year):  #接受Car实例所需的信息
        super().__init__(make,model,year)  #将父类与子类关联起来

my_tesla=ElectricCar('tesla','models',2016)
print(my_tesla.get_descriptive_name())

结果:

2016 Tesla Models

1.2 给子类定义属性和方法

class ElectricCar(Car):
    def __init__(self,make,model,year):
        super().__init__(make,model,year)
        self.battery_size=70  #添加新属性
    def describe_battery(self):  #添加新方法,为ElectricCar类所特有
        print("This Car has a "+str(self.battery_size)+"-kwh battery.")

my_tesla=ElectricCar('tesla','models',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()

结果:

2016 Tesla Models
This Car has a 70-kwh battery.

1.3 重写父类的方法
可在子类中定义一个与重写父类同名的方法,对其进行重写。
1.4 将实例用作属性

class Battery():  #定义一个新类,它没有继承任何类
    def __init__(self,battery_size=70):  设置形参默认值
        self.battery_size=battery_size
    def describe_battery(self):  #定义方法
        print("This Car has a "+str(self.battery_size)+"-kwh battery.") 

class ElectricCar(Car):
    def __init__(self,make,model,year):
        super().__init__(make,model,year)
        self.battery=Battery()  #将类Battery()作为self.battery的属性
    def get_range(self):
        if self.battery_size==70:
            range=240
        elif self.battery_size==85:
            range=270
        message="This car can go approximately "+str(range)
        message+=" miles on a full charge."
        print(message)

my_tesla=ElectricCar('tesla','models',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()  #实例调用
my_tesla.battery.get_range()  #实例调用

结果:

2016 Tesla Models
This Car has a 70-kwh battery.
This car can go approximately 240 miles on a full charge.

2、导入类
2.1 导入单个类
from model_name import class
2.2 在一个模块中存储多个类
2.3 从一个模块中导入多个类
from model_name import class_name1,class_name2 #各类中间用逗号,隔开
2.4 导入整个模块
import model_name
2.5 导入模块中的所有类
from model_name import *
2.6 从一个模块中导入另一个模块
from model_name1 import class1
from model_name2 import class2
3、Python标准库

from collections import OrderedDict  #OrderedDict可记录键-值对的添加顺序
favorite_languages=OrderedDict() #创建一个实例,并存储到变量中
favorite_languages['jen']='python'
favorite_languages['sarah']='c'
favorite_languages['edward']='ruby'
favorite_languages['phil']='Python'

for name,language in favorite_languages.items():
    print(name.title()+"'s favorite_languages is "+language.title()+".")

结果:

Jen's favorite_languages is Python.
Sarah's favorite_languages is C.
Edward's favorite_languages is Ruby.
Phil's favorite_languages is Python.

文件和异常
1、从文件中读取数据
1.1 读取整个文件

with open('file\\pi_digits.txt') as file_object:    #任何使用前都要打开文件,open()函数接受参数为要打开的文件的名称,与当前文件同目录
    contents=file_object.read() #用read()方法读取文件全部内容 
    print(contents)

pi_digits.txt:

3.1415926535
  8979323846
  2643383279

结果:

3.1415926535
  8979323846
  2643383279

1.2 逐行读取

file_name='E:\\Python\\file\\pi_digits.txt' #绝对路径查找文件位置
with open(file_name) as file_object:
   for file in file_object:    #使用for循环读取每行内容
       print(file)

结果:

3.1415926535    #空白行变多了,因为文件每行末尾都有一个看不见的换行符,print语句也会加上一个换行符

  8979323846

  2643383279

1.3 创建一个包含文件各行内容的列表

file_name='E:\\Python\\file\\pi_digits.txt' #绝对路径查找文件位置
with open(file_name) as file_object:    #使用with时,open()返回的对象只在with代码块内可用
    lines=file_object.readlines()   #将文件的各行存储在一个列表中,可在with代码块外使用该列表
for line in lines:
    print(line.rstrip())  #用rstrip()函数消除空白行

结果:

3.1415926535
  8979323846
  2643383279

1.4 使用文件内容

file_name='E:\\Python\\file\\pi_digits.txt' #绝对路径查找文件位置
with open(file_name) as file_object:    #使用with时,open()返回的对象只在with代码块内可用
    lines=file_object.readlines()

pi_string=''
for line in lines:
    pi_string+=line.rstrip()
print(pi_string)
print(len(pi_string))

结果:

3.1415926535  8979323846  2643383279
36

注意:读取文本文件时,python将其中的所有文本都解读为 字符串。如果读取的不是数字,并要将其用作数值使用,就必须使用int()将其转换为整数,或使用float()将其转换为浮点数

1.5 圆周率值中包含你的生日吗

file_name='E:\\Python\\file\\pi_digits.txt' #绝对路径查找文件位置
with open(file_name) as file_object:    #使用with时,open()返回的对象只在with代码块内可用
    lines=file_object.readlines()

pi_string=''
for line in lines:
    pi_string+=line.strip()
birthday=input("please input your birthday such as (0310):")
if birthday in pi_string:
    print("Your birthday appars in the first million digits of pi.")
else:
    print("Your birthday does not appars in the first million digits of pi.")

如果:

please input your birthday such as (0310):1128
Your birthday does not appars in the first million digits of pi.

2、写入文件
2.1 写入空文件

file_name='programming.txt'
with open(file_name,'w') as file_object:  #'w'表示写入模式,若文件不存在,则open()自动创建它
    file_object.write("I love python.")

结果:


image.png

2.2 写入多行

file_name='programming.txt'
with open(file_name,'w') as file_object:
    file_object.write("I love python.\n")
    file_object.write("I love creating new games.\n")

结果:


image.png

2.3 附加到文件

file_name='programming.txt'
with open(file_name,'a') as file_object:    #'a'表示附加模式,将内容附加到文件末尾,而不是覆盖到文件原来的内容
    file_object.write("He love JavaScript.\n")
    file_object.write("He also love creating new games.\n")

结果:


image.png
上一篇下一篇

猜你喜欢

热点阅读