九. 类
1.创建类
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性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!")
方法init(),类在创建实例时,会自动运行init()方法
类中的所有方法参数必须有self,且在其他参数最前面,这样实例才能够访问类中的属性和方法
2.访问类属性
my_dog = Dog("willie",6)
print("My dog's name is "+ my_dog.name.title()+ ".")
print("My dog is " + str(my_dog.age) + "years old.")
#My dog's name is Willie.
#My dog is 6years old.
3.调用类方法
my_dog.sit()
my_dog.roll_over()
#Willie is now sitting.
#Willie rolled over!
4.继承
class Car(object):
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
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
def fill_gas_tank(self):
print ("This car need a gas tank!")
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super(ElectricCar,self).__init__(make, model, year)
"""电动汽车特有属性"""
self.battery_size = 70
"""电动汽车特有方法"""
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size))
"""重写父类方法"""
def fill_gas_tank(self):
print('重写父类方法')
my_tesla = ElectricCar('tesla', 'models', 2016 )
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
#2016 Tesla Models
#This car has a 70
#重写父类方法
5.导入模块中的类
创建animal.py文件
class Cat():
def __init__(self):
print('创建猫实例')
class Dog():
def __init__(self):
print("创建狗实例")
创建index.py文件
from animal import Cat,Dog
#或者 from animal import *
my_dog = Dog()
my_cat = Cat()
十. 文件
1.从文件中读取数据
创建pi_digits.txt文件
3.1415926535
8979323846
2643383279
创建file_reader.py文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
#3.1415926535
# 8979323846
# 2643383279
逐行读取---rstrip 可去除空白行
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
#3.1415926535
# 8979323846
# 2643383279
2. 写文件,
打开文件时,可指定读取模式 读取模式 ('r' )、写入模式 写入模式 ('w' )、附加模式 附加模式 ('a' )或让你能够读取和写入文件的模式('r+' )。如果你省略了模式实参,Python将以默认的只读模式打开文件。
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
网友评论