python基础知识之类和文件

python—class

1. Class Syntax

  • 使用class 关键字声明一个类
  • 使用__init__() 函数进行类的初始化
  • 类中变量和方法的定义
class Fruit(object):
    def __init__(self, name, color):
        self.name = name
        self.color = color
    def description(self):
        print "I'm a %s %s" % (self.name, self.color)
lemon = Fruit("lemon", "yellow")

2. 继承

class Shape(object):
    """Makes shapes!"""
    def __init__(self, number_of_sides):
        self.number_of_sides = number_of_sides

# Add your Triangle class below!
class Triangle(Shape):
    def __init__(self, side1, side2, side3):
        self.side1 = side1
        self.side2 = side2
        self.side3 = side3

super()

class Employee(object):
    def __init__(self, employee_name):
        self.employee_name = employee_name
    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 20
class PartTimeEmployee(Employee):
    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 12
    def full_time_wage(self, hours):
        return super(PartTimeEmployee, self).calculate_wage(hours)
milton = PartTimeEmployee("liujia")
print milton.full_time_wage(10)
#输出:200

File Input/Output

my_list = [i**2 for i in range(1,11)]
#以写的方式打开output.txt文件
my_file = open("output.txt", "r+")
for item in my_list:
    my_file.write(str(item) + '\n')
my_file.close()

这里写图片描述

#读文件
my_file = open("output.txt", "r")
print my_file.read()
my_file.close()

这里写图片描述

with/as

with open("text.txt", 'w') as textfile:
    textfile.write("Success!")

检查文件是否关闭

文件对象有一个closed属性,当closed = True时,说明文件已经关闭,当closed = False,说明文件没有关闭

with open("text.txt", "w") as my_file:
    my_file.write('love')
if my_file.closed == "False":
    my_file.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值