【小白程序圆python学习记】类&文件和异常

第九章 类

#创建狗
class Dog():
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def sit(self):
        print(self.name.title()+" is now sitting")
    def roll_over(self):
        print(self.name.title()+" rolled over!")

my_dog=Dog("xiao",5)
my_dog.sit()
my_dog.roll_over()
Xiao is now sitting
Xiao rolled over!
## 创建多个实例
my_dog=Dog("xiao",5)
your_dog=Dog("li",4)

print("My dog's name is"+ my_dog.name.title()+".")
print("My dog's "+str(my_dog.age)+"years old.")
my_dog.sit()
My dog's name isXiao.
My dog's 5years old.
Xiao is now sitting
print("My dog's name is"+ my_dog.name.title()+".")
print("My dog's "+str(my_dog.age)+"years old.")
your_dog.sit()
My dog's name isXiao.
My dog's 5years old.
Li is now sitting
#创建饭店(练习)
class restaurant():
    def __init__(self,name,type):
        self.name=name
        self.type=type
    def describe_restaurant(self):
        print(self.name.title())
    def open_restaurant(self):
        print(self.name.title()+" is opening!")


my_r=restaurant("xiao","zhongshi")
my_r.describe_restaurant()
my_r.open_restaurant()
Xiao
Xiao is opening!
# 创建汽车
class car():
    def __init__(self,make,model,year):
        self.make=make
        self.model=model
        self.year=year
    def get_descriptive_name(self):
        long_name=str(self.year)+" "+self.make+" "+self.model
        return long_name.title()

my_new_car =car("audi","a4","2016")
print(my_new_car.get_descriptive_name())
#先创建__init__形参,函数,返回值,指定实参,打印
2016 Audi A4

第十章 文件和异常

# 读取文件
with open("E:\学习\Python\代码.txt") as file_object:
    contents=file_object.read()
    print(contents)
#相对路径不通,可以使用绝对路径
12
456
# 逐行读取
file="E:\学习\Python\代码.txt"
with open(file) as file_object:
    for line in file_object:
        print(line)
12

456

5

666

8



999
file="E:\学习\Python\代码.txt"
with open(file) as file_object:
    for line in file_object:
        print(line.strip())-------消除空行
12
456
5
666
8

999
with open(file,"w") as file_object:   #如果出现 not writable报错,需要加上"w"变得可写入;读取模式为"r";附加模式为"a"
    file_object.write("i love you.")
with open(file) as file_object:
    for line in file_object:
        print(line)
i love you.
with open(file,"a") as file_object:   #附加模式为"a"不改变原内容
    file_object.write("\ni love you,too.")
with open(file) as file_object:
    for line in file_object:
        print(line)
i love you.i love you,too.

i love you,too.

i love you,too.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值