版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/itsxwz/article/details/82191333
1.类
#定义类
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is now sitting.")
my_dog = Dog('willie',6) #创建实例
my_dog.name #访问属性
my_dog.sit() #调用方法
#继承 电动车类继承车类
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
#将实例用作属性 (A类里面声明了一个B类的对象,类似)
class Car():
--snip--
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()
from car import Car #从car.py模块导入Car类
from car import Car, ElectricCar #从一个模块导入多个类
import car #导入整个模块
from module_name import * #导入模块中的所有类
2.文件和异常
#读取pi_digits.txt文件,并打印其内容
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
#逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
#写入空文件 没有则创建文件;有则先清空在写入(w方式) 附加到文件内容末尾(a方式)
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
- ZeroDivisionError 被除数为0异常
- FileNotFoundError 文件为找到异常
- try-except
- split() 方法分割一个字符串,返回一个列表 (类似分割字符串返回一个数组)
#json.dump() 存储数据
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
#json.load() 读取数据
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back, " + username + "!")
3.测试代码
import unittest
from name_function import get_formatted_name
assertEqual(a,b)
assertNotEqual(a,b)
assertTrue(x)
assertFalse(x)
assertIn(item,list)
assertNotIn(item,list)
#如果你在类中包含了setUp()方法,Python将先运行它,再运行各个以test_开头的方法