Python3.6学习记录

# -*- coding: utf-8 -*-

注释

“>>>:输出的结果”

pip安装

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python get-pip.py

变量、字符串操作

大小写:.title()首字母大写, .upper()全大写, .lower()全小写

例:

word  = 'aBcdEfg'
print(word.title())
>>>Abcdefg

word  = 'aBcdEfg'
print(word.upper())
>>>ABCDEFG

word  = 'aBcdEfg'
print(word.title())
>>>abcdef

合并(拼接):+ 制表符: \t 换行 :

删除空白: rstrip()删除右边空白, lstrip()删除左边空白,strip()删除左右空白

例:

word = ' Python '
print(word.rstrip())
>>>' Python'

word = ' Python '
print(word.lstrip())
>>>'Python '

word = ' Python '
print(word.strip())
>>>'Python'

数字

# 整数运算: + - * / 加减乘除   **乘方 2**3(2的3次方)  4**2(4的2次方) +=
3 / 2 = 1	##整数运算如果结果带小数点,只会显示小数点左边的结果,右边将忽略
a = 1	
a += 1	#+=表示将左边变量的值加上右边的值重新赋值给左边的变量
print(a)

浮点数:

0.1 + 0.2 = 0.3
3.0 / 2 = 1.5
3 / 2.0 = 1.5
3.0 / 2.0 = 1.5

求模(求余)运算符 (%),它将两个数相除并返回余数

print(4 % 3) #显示结果为1
print(6 % 3) #显示结果为0
print(8 % 6) #显示结果为2

求商运算符(//),它将两个数相除并返回商,不管余数

print( 12 // 6)	#结果为2
print( 15 // 4)	#结果为3
print( 12 // 3)	#结果为4

函数: str() 将数据转成字符串 , int()整数

列表:

列表-访问列表内容,从左至右,0为第一位

numbers = [1, 2, 3, 4]
word = ['a', 'b', 'c']
print(numbers[0])
>>>1

#不论列表多长,取最后一个值
print(numbers[-1])
>>>4

#从头开始,到第3个结束,不会取第3个
print(numbers[:2])
>>>[1, 2]

###从第三个开始,结列表结尾

print(numbers[2:]
>>>[3, 4]

#列表-修改、添加、删除列表元素

numbers = [1, 2, 3, 4]
word = ['a', 'b', 'c']

#修改指定位置的元素
numbers[1] = 6
print(numbers)
>>>[1, 6, 3, 4]

###添加元素,分两种,一是在列表末尾添加元素,一是在指定位置插入元素
word.append('e')
print(word)
>>>['a', 'b', 'c', 'e']

###在指定位置插入元素
word.insert(3, 'd')
print(word)
>>>['a', 'b', 'c', 'd', 'e']

###删除列表元素, 
print(numbers)
>>>[1, 6, 3, 4]

##del 直接删除指定的元素,	
del numbers[1]
print(numbers)
>>>[1, 3, 4]

##.pop()从列表最后删除并使用它的值,.pop(0),删除指定位置的值,并使用该值
print(numbers.pop())
>>>4
print(numbers)
>>>[1, 3]

##remove(),不知道元素位置时,直接指定要删除的元素值,
numbers.remove(3)
print(numbers)
>>>[1]

列表-组织列表

sort()对列表进行永久正序排序,无法恢复到原来状态,按字母顺序排列;sort(reverse=True)反序 例:

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
>>>['audi', 'bmw', 'subaru', 'toyota']
cars.sort(reverse=True)
print(cars)
>>>['toyota', 'subaru', 'bmw', 'audi']



sorted()对列表进行临时正序排序;reverse()对当前列表的顺序进行永久反序排序	
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars))	#临时正序

print(sorted(cars, key=None, reverse=True))	#临时反序

cars.reverse()	#永久反序,再执行一次就还原了
print(cars)

列表-列表长度:

len(cars)

列表-操作列表

cars = ['bmw', 'audi', 'toyota', 'subaru']
for car in cars:
	print(car)

cats = []
if cats:
	for cat in cats:
		print(cat)
else:
	print('The list it is empty!')

列表-数值列表

range()函数,指定一个数字范围

例:range(1, 5),从1开始,到5结束,不包含5

numbers = list(range(1, 5))
print(numbers)
[1, 2, 3, 4]

例:range(2, 10, 2),从2开始,到11结束,每隔2生成一个值。那么生成的结果就是2,4,6,8

numbers = list(range(2, 10, 2)
print(numbers)
#循环打印出1-1000。
for i in range(1,1001):
	print(i)
#将生成的数字加入指定空列表
numbers = []
for i in range(1, 11):
	numbers.append(i)
print(numbers)

列表-数字统计: min()最小值,max()最大值, sum()求和

numbers = list(range(1, 11))
print(min(numbers))
print(max(numbers))
print(sum(numbers))

列表-复制列表: 前面是新列表,后面是旧列表,可以是全部,也可以是指定的分片内容。复制列表后对新旧列表添加的元素不会出现在另一个列表中。

new_numbers = numbers[:] 
new_numbers = numbers[5:]
new_numbers = numbers[:6]
new_numbers = numbers[3:7]

列表转字符串,通过''.join来将列表转为字符串,前面的单引号中可以添加任何字符做转换后的分隔符,

list1 = ['a', 'b', 'c', 'd']
str_list1 = ''.join('list1')
str_list2 = ','.join('list1')
print (str_list1)
	abcd
print (str_list2)
   a,b,c,d

元组

跟列表类似,不过是用小括号包含,且元组中的元素不能修改(可以通过变量的形式修改)。dimensions = (200, 50)。读取、遍历操作形式跟列表相同。

if语句

如果条件测试的结果为True ,Python就会执行紧跟在if 语句后面的代码;否则Python将忽略这些代码。

cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:	
	if car == 'bmw':
		print(car.upper())
	else:
		print(car.title())
#== 判断是否相等,如果值是字母,可以用之前学到的 lower()函数将其转换成全小写来对比。
#!= 不等于
if 1 !=2:
	print("ba la la la~~~")

#and 有多个条件必须同时满足时,用and
if  1==1 and 3>2:
	print("ba lalala~~~")

#or 有多个条件只需满足其中之一时,用 or
if 1==2 or 3>2:
	print("ba lalaaa~~~")

#in 检测前面的值是否包含在后面的列表之中
list_test = ['a', 'b', 'c']
value = 'a'
if value in list_test:
	print(value)

#if-else:在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作
如果条件满足,就打印ba lalaaa~;否则,就打开hehe~~~
if 1 > 2:
	print('ba lalaaa~~')
else:
	print('hehe~~~')

#if-elif-else:
#依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。
age = 18

if age < 5:
	print('bbb')
elif age <18:
	print("aaaa")
else:
	print('ccc')

还有以下类似的情况,就不一一举例了

if-elif-elif-elif-esle:
if-elif-elif-elif……
if-if-if……

字典

以大括号{}包含,每个键对应一个值。

ditc_test = {
	'key1': 'value1',
	'key2': 'value2',
	'key3': 'value3'
}

字典-修改:

ditc_test['key1'] = 'value5'

字典-删除:

del ditc_test['key1']

简单取值:

ditc_test = {
	'key1': 'value1',
	'key2': 'value2',
	'key3': 'value3'
}
print(ditc_test['key1'])

字典-取值方法:items()显示所有,sorted()排序,key()取键, values()取值, set()除去重复项。

例:

1、items(),通过for循环可以依次取出所有指定值

ditc_test = {
	'key1': 'value1',
	'key2': 'value2',
	'key3': 'value3'
}
for key, value in distc_test.items():
	print(key + ':' + value)

2、sorted(),对结果调用sorted()函数,最终结果将会按顺序显示结果

ditc_test = {
	'key1': 'value3',
	'key2': 'value2',
	'key3': 'value1'
}
for value in sorted(ditc_test.values()):		
	print(value)

3、key(),取字典的键而不显示值

ditc_test = {
	'key1': 'value1',
	'key2': 'value2',
	'key3': 'value3'
}

for key in ditc_test.key():		
	print(key)
#取键有两种写法,key()可加可不加,上下两个for循环的结果是一样的
for key in ditc_test:
	print(key)

4、value(),取字典的值而不显示键

ditc_test = {
	'key1': 'value1',
	'key2': 'value2',
	'key3': 'value3'
}
for value in ditc_test.values():
	print(value)
>>>value1
>>>value2
>>>value3

5、set(),当字典中部分键的值相同时,可以通过set()函数去重。

ditc_test = {
	'key1': 'value1',
	'key2': 'value2',
	'key3': 'value1'
}
for value in set(ditc_test.values()):
	print(value)
>>>value1
>>>value2

字典-嵌套

当一个字典无法存储同类型的第二个信息时,就可以用到嵌套。即将字典嵌套到列表中

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}

aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
	print(alien)

将字典存储在列表中以及取值示例:

aliens = []
for number in range(0, 30):
	new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
	aliens.append(new_alien)
for i in aliens[:3]:
	if i['color'] == 'green':
		i['color'] = 'yellow'
		i['points'] = 10
		i['speed'] = 'medium'
for i in aliens[:5]:
	print(i)

将列表存储在字典中以及取值示例:

aliens = {
		'color': ['green', 'yellow', 'red'],
		'points': [5, 10, 15],
		'speed': ['slow', 'medium', 'fast']
		}

colors = ['green', 'yellow', 'red']
points = [5, 10, 15]
speed = ['slow', 'medium', 'fast']
aliens = {
		'color': colors,
		'points': points,
		'speed': speed
		}

for key, value in aliens.items():
	print(key)
	for i in value:
		print(i)

在字典中存储字典以及取值示例:

users = {
		'barry': {
				'first_name': 'barry',
				'last_name': 'allen',
				'location': 'center city'
				},
		'cisco': {
				'first_name': 'cisco',
				'last_name': 'ramon',
				'location': 'center city'
				}
		}
for key, value in users.items():
	print(key)
	print('full name:' + value['first_name'] + ' ' + value['last_name'])
	print('location:' + value['location'])

While循环

input()函数

让程序暂停,等待用户输入文本,并将输入的内容存储在变量中,方便调用

message = input('Tell me something, and I will repeat it back to you: ')
print(message)

int()函数:获取数值输入

以下两份代码执行完之后虽然输出内容一样,但第一份其实是将数字以文本形式输出 所以第一份代码执行后会报错

a = input("please enter first number: ")
b = input("please enter last number: ")
print(a * b)

a = int(input("please enter first number: "))
b = int(input("please enter last number: "))
print(a * b)

while循环语句:

a = 1
while a <= 10:
	print(a)
	a += 1

break:退出循环,不光在while中可以用,所有循环语句中都能使用break退出当前循环

#当用户输入quit时,退出当前循环
input_text = 'please enter something:'
input_text += "\nEnter 'quit' to end the progarm."
while True:
	messages = input(input_text)
	if messages == 'quit':
		break
	else:
		print(messages)

continue:要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句,它不像break 语句那样不再执行余下的代码并退出整个循环。

#在循环中使用 continue,以下代码为,如果a能被2整除,则继续循环,否则就打印a的值
a = 0
while a <= 10:
	a += 1
	if a % 2 == 0:
		continue
	print(a)

while循环处理列表和字典

#在列表之间移动元素
user_1 = ['tom', 'jerry', 'barry', 'iris', 'joe']
user_2 = []	
while user_1:
	user_2.append(user_1.pop())
print(user_1)
print(user_2)

#删除包含特定值的所有列表元素
user_1 = ['tom', 'jerry', 'barry', 'iris', 'joe', 'barry', 'iris', 'joe']
print(user_1)
while 'iris' in user_1:
	user_1.remove('iris')
print(user_1)

#循环提示用户输入信息到字典,直至用户要求退出
user_info = {}

while True:
	name = input('please enter you name: ')
	age = int(input('please enter you age: '))
	user_info[name] = age
	repeat = input("would you like to let another person respond? (yes/no)")
	if repeat.lower() == 'no':
		break
print(user_info)

函数

定义函数

def greet_user():		#使用def 关键字来定义函数,后面接函数名,括号内指定需要的信息
	print('Hello!')		#代码行,具体的操作

greet_user()			#调用该函数,也可以在括号中指定需要的信息

向函数传递信息

def greet_user(username):
	print("Hello, " + username.title() + "!")

greet_user('jerry')

第一阶段,形参,实参均为空值,直接显示打印内容

def greet_user():   #定义函数
   print('Hello!') #要打印的内容
greet_user()        #调用函数,

第二阶段,形参为变量username,实参为手动输入内容,liqiao.将实参的值写到形参变量中,并打印出来,打印格式为首字母大写。

def greet_user(username):
	print('Hello, ' + username.title() + '!')
greet_user('liqiao')

第三阶段,形参为变量username, 实参为变量usernames,实参变量提前定义好了,内容为dier.最后打印显示。

usernames = 'dier'
def greet_user(username):
	print('Hello, ' + username.title() + '!')
greet_user(usernames)

第四阶段,形参为变量username, 实参为变量usernames,提前设置一个列表,将姓名记录,通过for循环将列表中的值依次放到实参变量中并进行打印

current_users = ['admin', 'code', 'developer', 'manager', 'check']
def greet_user(username):
print('Hello, ' + username.title() + '!')

for usernames in current_users:    
greet_user(usernames)

如果有多个形参,在调用函数通过实参给形参赋值时,要么按形参的位置,依次赋值;要么按形参名称赋值

#位置实参:按形参顺序赋值
def make_shirt(shirt_size, shirt_style):
	print('shirt size is ' + shirt_size.upper() + ', shirt style is ' + shirt_style + '.')
make_shirt('m', 'I love python')

关键字实参:按形参名称赋值

def make_shirt(shirt_size, shirt_style):
	print('shirt size is ' + shirt_size.upper() + ', shirt style is ' + shirt_style + '.')
make_shirt(shirt_style = 'I love python', shirt_size = 'm')

默认值

def describe_pet(pet_name, animal_type='dog'):
	print("I have a " + animal_type  + ", name is " + pet_name.title() + "." )

describe_pet(pet_name='wille')

等效的函数调用

def describe_pet(pet_name, animal_type='dog'):

#下面两行函数调用的结果一样
describe_pet(pet_name='wille')
describe_pet('wille')

#下面三行函数调用的结果一样
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

返回简单值 return函数

def get_full_name(first_name, last_name):
	full_name = first_name.title() + ' ' + middle_name.title() + ' ' + last_name.title()
	return full_name

print(get_full_name('barry' , 'allen'))

让实参变成可选,例如有的人的名字由三部分组成,有的只有两部分。这时就可以将形参设置一个空值。 下面的例子中,将middle_name设置为空值,这样就算只输入first_name 和last_name,也不会报错。

def get_full_name(first_name, last_name, middle_name=''):
	full_name = first_name.title() + ' ' + middle_name.title() + ' ' + last_name.title()
	return full_name

print(get_full_name('barry' , 'allen'))
print(get_full_name('emily', 'rickards', 'bett'))

返回列表、字典 函数可返回任何类型的值。

返回列表

def get_list(first, last):
	full_list = [first, last]
	return full_list

print(get_list('firstttt', 'lastttt'))

返回字典

def get_full_name(first_name, last_name):
	full_name = {'first_name': first_name, 'last_name': last_name}
	return full_name

print(get_full_name('barry' , 'allen'))

传递列表

def greet_users(names):
	for name in names:
		msg = "Hello " + name.title() + "!"
		print(msg)
username = ['barry', 'iris', 'tom', 'joe', 'jerry']
greet_users(username)

在函数中修改列表

通过for循环将一个列表中的元素添加到另一个列表中

def print_models(unprinted_designs, completed_models):
	for i in unprinted_designs:
		print("Printing model:" + i)
		completed_models.append(i)

def show_completed_models(completed_models):
	for value in completed_models:
		print(value)

unprinted_designs = ['a', 'b', 'c', 'd']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

通过while循环将一个列表中的元素移到另一个列表中

def print_models(unprinted_designs, completed_models):
	while unprinted_designs:
		desings = unprinted_designs.pop()
		print("Printing model: " + desings)
		completed_models.append(desings)

def show_completed_models(completed_models):
	for i in completed_models:
		print(i)

unprinted_designs = ['a', 'b', 'c', 'd']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

传递任意数量的实参,形参toppings前面的*表示创建一个名为toppings的空元组,

def make_pizza(*toppings):
	for i in toppings:
		print('Add toppings: ' + i)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

传递任意数量的实参,形参toppings前面的**表示创建一个名为toppings的空字典

'''
该函数包涵两个基本形参,还能接受任意数量的关键字实参,当调用函数时除了必不可少的品牌和型号外,还可以指定其它信息,例如颜色和配件
'''
def make_car(brands, models, **options):

	#创建一个空字典,用来放所有的信息
	profile = {}	

	#设置键-值的关系
	profile['brands'] = brands	
	profile['models'] = models	

	#从options中读取指定的键-值
	for key, value in options.items():	
		profile[key] = value	

	#调用函数
	return profile		

#指定基本信息和要添加的其它选项(颜色、配件)
car = make_car('subaru', 'outback', color='blue', tow_package=True)	

print(car)

将函数存储在模块中,导入整个模块

先新建一个名为pizza.py的文件,并在其中创建一个函数。如下:

def make_pizza(size, *toppings):
	print('Making a ' + str(size) + '-inch pizza with the following toppings:')
	for i in toppings:
		print('- ' + i)

再新建另一个名为make_pizza.py的文件,导入并调用pizza.py中的函数

import pizza

pizza.make_pizza(16, 'mushrooms', 'green peppers', 'extra cheese')

执行make_pizza.py这个文件,python会在后台自动导入pizza.py的内容到make_pizza.py中并完成代码执行

导入指定的函数;

导入单个的函数时,在引用时就不需要文件名加模块名称了 先新建一个名为pizza.py的文件,并在其中创建一个函数。如下:

def make_pizza(size, *toppings):
	print('Making a ' + str(size) + '-inch pizza with the following toppings:')
	for i in toppings:
		print('- ' + i)

再新建另一个名为make_pizza.py的文件,导入并调用pizza.py中的make_pizza函数

from pizza import make_pizza

make_pizza(16, 'mushrooms', 'green peppers', 'extra cheese')

使用as给模块指定别名,调用模块中的函数更轻松

先新建一个名为pizza.py的文件,并在其中创建一个函数。如下:

def make_pizza(size, *toppings):
	print('Making a ' + str(size) + '-inch pizza with the following toppings:')
	for i in toppings:
		print('- ' + i)

再新建另一个名为make_pizza.py的文件,导入pizza.py中的所有函数,并设置别名 p

import pizza as p

p.make_pizza(16, 'mushrooms', 'green peppers', 'extra cheese')

导入模块中的所有函数,跟导入整个模块的效果一样,不过在调用方法上有所区别

先新建一个名为pizza.py的文件,并在其中创建一个函数。如下:

def make_pizza(size, *toppings):
	print('Making a ' + str(size) + '-inch pizza with the following toppings:')
	for i in toppings:
		print('- ' + i)

再新建另一个名为make_pizza.py的文件,使用 * 导入pizza.py中的所有函数

from pizza import *

make_pizza(16, 'mushrooms', 'green peppers', 'extra cheese')

通过class 来创建类,类的首字母为大写。 以下是一个例子,创建了一个名为Dog的类,并在其中制定了部分方法(函数),最后对类进行了调用

class Dog():

	def __init__(self, name, age):
		self.name = name
		self.age = age
	def sit(self):
		print(self.name.title() + ' is no sitting.')

	def roll_over(self):
		print(self.name.title() + ' rolld over!')

my_dog = Dog('wille', 3)
print("My dog's name is " + my_dog.name.title() + '.')
my_dog.sit() 
my_dog.roll_over()

方法:类中的函数称为方法,之前所有的函数都适用于方法。__init__()是一个特殊的方法,每次根据类创建新实例时,Python都会自动运行它。这个方法的开头和末尾各有两个下划线,用于做约定,防止跟其它方法发生名称冲突。

使用类和实例:给属性指定默认值、修改属性的值、对属性的值进行递增

class Car():

	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("这车目前的行驶里程是" + str(self.odometer_reading) + '英里。')

	def update_odometer(self, mileage):
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("不能将里程表往回拨!")

	def increment_odoment(self, miles):
		self.odometer_reading += miles #对属性的值进行递增

my_car = Car('audi', 'a4', 2016)
print(my_car.get_descriptive_name)	
my_car.	update_odometer(20) #修改属性的值
my_car.increment_odoment(10)
my_car.read_odometer()

继承

	###子类的方法__init__():创建子类实例时,需要先对父类的所有属性赋值。
class Car():

	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("这车目前的行驶里程是" + str(self.odometer_reading) + '英里。')

	def update_odometer(self, mileage):
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("不能将里程表往回拨!")

	def increment_odoment(self, miles):
		self.odometer_reading += miles

class Battery():

	def __init__(self, battery_size=70):
		self.battery_size = battery_size

	def describe_battery(self):
		'''显示电池容量'''
		print("这车目前电池电量还有" + str(self.battery_size) + '%。')

class ElectricCar(Car):  #括号中指定需要继承类的名称

	def __init__(self, make, model, year):
		super().__init__(make, model, year)		#继承父类的三个形参
		self.battery = Battery()

my_tesla = ElectricCar('tesla', 'model s', 2018)
print(my_tesla.get_descriptive_name())	
my_tesla.read_odometer()

'''这里的battery是调用的ElectricCar类中的self.battery,所以可以正确调用到电池容量。'''
my_tesla.battery.describe_battery()		

重写父类

比如A类为B类的父类,但A类中有某一个方法(函数)在B类中不适合,则可以在B类中重写这个方法。

class Car():

	def __init__(self, make, model, year):
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0
		self.gas_tank = 80

	def get_descriptive_name(self):
		long_name = str(self.year) + ' ' + self.make + ' ' + self.model 
		return long_name.title()

	def read_odometer(self):
		print("这车目前的行驶里程是" + str(self.odometer_reading) + '英里。')

	def update_odometer(self, mileage):
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("不能将里程表往回拨!")

	def increment_odoment(self, miles):
		self.odometer_reading += miles

	def fill_gas_tank(self):	#父类定义的一个方法,但在电动车上不适用
		print("这车目前邮箱剩余油量:" + str(self.gas_tank) +"%")

my_car = Car('audi', 'a4', 2016)
print(my_car.get_descriptive_name)	
my_car.	update_odometer(20)
my_car.increment_odoment(10)
my_car.read_odometer()
my_car.fill_gas_tank()

class Battery():

	def __init__(self, battery_size=70):
		self.battery_size = battery_size

	def describe_battery(self):
		'''显示电池容量'''
		print("这车目前电池电量还有" + str(self.battery_size) + '%。')

class ElectricCar(Car):

	def __init__(self, make, model, year):
		super().__init__(make, model, year)		#继承父类的三个形参
		self.battery = Battery()


	def fill_gas_tank(self):	#继承父类(Car)后,电动车对这个方法不适用,需要重新定义。
		'''电动汽车没有油箱'''
		print('电动汽车不需要油箱!')

my_tesla = ElectricCar('tesla', 'model s', 2018)
print(my_tesla.get_descriptive_name())	
my_tesla.read_odometer()

'''这里的battery是调用的ElectricCar类中的self.battery,所以可以正确调用到电池容量。'''
my_tesla.battery.describe_battery()
my_tesla.fill_gas_tank()	

导入类:因为类中放的也是函数,所以导入方法跟函数类似

导入一个类,先创建一个名为car.py的文件,然后在其中写一个Car的类,在另外一个文件中进行导入

cat.py

class Car():

	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("这车目前的行驶里程是" + str(self.odometer_reading) + '英里。')

	def update_odometer(self, mileage):
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("不能将里程表往回拨!")

	def increment_odoment(self, miles):
		self.odometer_reading += miles

my_car.py
from cat import Car

my_car = Car('audi', 'a4', 2016)
print(my_car.get_descriptive_name)	
my_car.update_odometer(20)
my_car.increment_odoment(10)
my_car.read_odometer()

执行my_car.py即可

在一个模块中存储多个类

car.py

class Car():

	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("这车目前的行驶里程是" + str(self.odometer_reading) + '英里。')

	def update_odometer(self, mileage):
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("不能将里程表往回拨!")

	def increment_odoment(self, miles):
		self.odometer_reading += miles

class Battery():

	def __init__(self, battery_size=70):
		self.battery_size = battery_size

	def describe_battery(self):
		'''显示电池容量'''
		print("这车目前电池电量还有" + str(self.battery_size) + '%。')

class ElectricCar(Car):

	def __init__(self, make, model, year):
		super().__init__(make, model, year)		#继承父类的三个形参
		self.battery = Battery()
my_electric_car.py
from car import ElectricCar

my_tesla = ElectricCar('tesla', 'model s', 2018)
print(my_tesla.get_descriptive_name())	
my_tesla.read_odometer()

'''这里的battery是调用的ElectricCar类中的self.battery,所以可以正确调用到电池容量。'''
my_tesla.battery.describe_battery()	

执行my_electric_car.py即可

从一个模块中导入多个类,引用前面的car.py文件。

my_cars.py

from car import Car, ElectricCar

my_tesla = ElectricCar('tesla', 'model s', 2018)
print(my_tesla.get_descriptive_name())	
my_tesla.read_odometer()

'''这里的battery是调用的ElectricCar类中的self.battery,所以可以正确调用到电池容量。'''
my_tesla.battery.describe_battery()	

导入整个模块

import car

导入模块中的所有类

from car import *

在一个模块中导入另一个模块

方法跟前面相同,思路如下:分别有A B两个模块文件,B 继承了A 的类,那么需要先在B模块文件中导入继续的A类,C文件在需要分别使用A B两个模块时,只需导入A B模块即可。 再复杂点,A B C三个模块文件,C继承B,B继承A,文件D需要导入C时,只需要C B分别在各自的文件中准确导入了继承的模块后,D可以直接通过C调用,而不需要再导入A B两个模块。

文件

从文件中读取数据 新建一个文件 pi_digits,输入如下内容:

cat pi_digits

	3.1415926535
	  8979323846
	  2643383279

新建file_read.py文件,来读取上一个文件的内容:

file_read.py

with open('pi_digits') as file_object:
contents = file_obiect.read()
print(contents.rstrip())

解释

open() #打开文件, as #给打开的文件取个别名(赋值给变量),方便后面操作。默认是跟执行文件在同一目录。 read() #读取文件的全部内容 rstrip() #之前学到过的,删除右边的空格。可以去掉对比一下效果。 #这里调用了open(),却没有close(),是因为使用了with关键字,作用是在访问文件后自动将其关闭。

文件路径,以下只是linux环境下的路径写法,windows环境中路径为反斜杠\

相对路径

	with open(‘text_file/filename’) as file_object:

绝对路径

	with open(‘/home/root/other_files/text_file/filename’) as file_object:

逐行读取:有时需要检查其中的每一行。则需要通过for 循环来实现

file_read.py

filename = 'pi_digits'

with open(filename) as file_object:
	for line in file_object:
		print(line.rstrip())

创建一个包含文件各行内容的列表:使用with关键字时,open()返回的文件内容只能在with代码块内可用。如果要在with代码块以外的地方使用,可以将内容存储在一个列表中。然后在其它地方调用。

file_read.py

filename = 'pi_digits'	
with open(filename) as file_object:
	lines = file_object.readlines()

pi_string = ''

for line in lines:
	pi_string += line.strip()

print(pi_string)
print(pi_string[:20] + '……')    #显示指定长度的数字

写入文件:跟读取类似,不过还需要在调用 open()时提供另外一个实参

filename = 'programming.txt'

with open(filename, 'w') as file_object:
	file_object.write('写入文件!\n')
	file_object.write('写入文件!~~~~~~~~~\n')

解释:

w #实参,表示写入,如果文件里有内容,会被覆盖 a #追加,如果文件里有内容,不会覆盖,在后面追加写入的内容。 r #读取文件时的默认值,可写可不写。 write #写入函数

filename = 'user_list'	
while True:
	names = input("请输入您的姓名(如果想退出,请输入’quit’):")
	if names.lower() == 'quit':
		break
	else:	
		with open(filename, 'a') as f:
			f.write(names)
			f.write("! 欢迎~~~\n")

异常

当发生python不知所措的错误时,会创建一个异常对象,如果未对该异常进行处理,程序将停止。 以下例子为使用try-except

divsion.py
print(5/0)

处理异常

ZeroDivisionError

try:
	print(5/0)
except ZeroDivisionError:
	print("You can't divsion by zero!")

FileNotFoundError

filename = 'abc.txt'

try:
	with open(filename) as f:
		print(f.read().rstrip())
except 	FileNotFoundError:
	print(filename + "这个文件不存在,请检查后再试")

使用try-except时配合else

print("请根据提示依次输入两个数字,系统会进行除法运算。")
print("如果想退出,请输入'q'")	
while True:
	first_number = input("\n请输入第一个数字:")

	if first_number == 'q':
		break
	second_number = input("\n请输入第二个数字:")
	try:
		answer = int(first_number) / int(second_number)
	except ZeroDivisionError:
		print("0不能做除数,请输入一个非0的数字!")
	else:
		print(answer)

报错时不做任何提示 直接把except下的print()改成 pass

filename = 'abc.txt'

try:
	with open(filename) as f:
		print(f.read().rstrip())
except 	FileNotFoundError:
	pass

分析文本

split()		# 它根据一个字符串创建一个单词列表。

以下代码中,我有准备一个名为Napoleon.txt的文件,但没有python这个文件,运行后会显示Napoleon.txt的单词数,然后提示没有python这个文件

def check_book_number(filename):

	try:
		with open(filename) as file_object:
			contents = file_object.read()
	except FileNotFoundError:
		print(filename + "这个文件不存在,请检查后再试")
	else:	
		print(filename + " 这本书总共有" + str(len(contents.split())) + "个单词")

filenames = ["Napoleon.txt", 'python']	
for i in filenames:
	check_book_number(i)

count()		# 统计指定内容出现的次数

def check_book_number(filename, wrod):

	try:
		with open(filename) as file_object:
			contents = file_object.read()
	except FileNotFoundError:
		print(filename + "这个文件不存在,请检查后再试")
	else:	
		print(filename + " 这本书总共有" + str(len(contents.split())) + "个单词")
		print(filename + " 这本书中," + wrod + " 这个单词出现了" + str(contents.lower().count(wrod)) + "次")

filenames = ["Napoleon.txt", 'python']
for i in filenames:
	check_book_number(i, 'napoleon')

存储数据

使用json.dump()来存储数据

'''导入json模块'''		
import json

'''新建一个用于导入的列表'''
numbers = [2, 3, 5, 7, 11, 13]

'''定义要写入的文件名'''
f_name = 'numbers.json'

'''通过with open  打开前面定义的文件,并通过json.dump把前面创建的列表内容导入新建的文件中'''
with open(f_name, 'w') as f_obj:
	json.dump(numbers, f_obj)

使用json.load()来读取数据

'''导入json模块'''		
import json

'''指定要读取的文件名'''
f_name = 'numbers.json'

'''通过with open打开文件,并通过json.load来读取文件内容,打印出读取的结果'''
with open(f_name) as f_obj:
	numbers = json.load(f_obj)

'''打印出读取的结果'''	
print(numbers)
  • pygame

  • rect()

  • left

  • top

  • right

  • bottom

  • left : 矩形左边的X坐标 150 ---->图片中的A点

  • top: 矩形顶部的Y坐标 75 ---->图片中的B点

  • right : 矩形右边的X坐标 260 ----->图片中的C点

  • bottom: 矩形底部的Y坐标 120 ------->图片中的D点

python获取网页指定信息,例如csrf-token

需要用到的库有requests BeautifulSoup

比如获取上图中 csrf-token 的值,过滤的关键在于 soup.find(‘meta’,{‘name’:’csrf-token’})[‘content’]

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup

headers = {"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537.36"}

url = 'https://red.zizi.com.cn/login'
client = requests.Session()
login_page = client.get(url=url, headers=headers)
soup = BeautifulSoup(login_page.content,"html.parser")
csrf = soup.find('meta', {'name':'csrf-token'})['content']
print(csrf)

python3通过re加正则表达式,过滤指定内容报“TypeError: cannot use a string pattern on a bytes-like object”错误,解决方法

import requests
import re

headers = {"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537.36"}

url = "http://192.168.100.10:9000/j_acegi_security_check"

d = {"from":"/",
	"j_username":"ituser",
	"j_password":"Nsfocus111",
	"Jenkins-Crumb":"820a53b6613a347cb5aafcecb557487f",
	"json":{"j_username": "ituser", "j_password": "Nsfocus111", "from": "/", "Jenkins-Crumb": "820a53b6613a347cb5aafcecb557487f"},
	"Submit":"log in"
}

s = requests.session()
r = s.post(url, headers=headers, data=d)
t = re.findall(r'<b>(.+?)</b>', r.content) #报错代码
t = re.findall(r'<b>(.+?)</b>', r.content.decode('utf-8')) #加上用decode('utf-8')解码即可

python3.6登录website,辅助软件fiddler,用于抓取登陆过程以及需要的信息

一、直接提交参数进行登录,以jenkins登录为例

# -*- coding: utf-8 -*-
import requests
import re

headers = {"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537.36"}

url = "http://192.168.100.10:9000/j_acegi_security_check"

d = {"from":"/",
	"j_username":"ituser",
	"j_password":"111111111",
	"Jenkins-Crumb":"820a53b6613a347cb5aafcecb557487f",
	"json":{"j_username": "ituser", "j_password": "Nsfocus111", "from": "/", "Jenkins-Crumb": "820a53b6613a347cb5aafcecb557487f"},
	"Submit":"log in"
}

#通过session()来保持会话
s = requests.session()

#提交信息
r = s.post(url, headers=headers, data=d)

#使用re 过滤出登录后的信息,用于判断是否登录成功,python3需要加.decode('utf-8')来解码
t = re.findall(r'<b>(.+?)</b>', r.content.decode('utf-8'))
print(t[0])
print(t[1])

二、需要携带crsf-token,以redmine登录为例

# -*- coding: utf-8 -*-
import requests
import re
from bs4 import BeautifulSoup

headers = {"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537.36"}

url = "https://red.zizi.com.cn/login"
s = requests.session()

#先请求一次页面,生成crsf-token
c = s.get(url, headers=headers)
soup = BeautifulSoup(c.content,"html.parser")

#通过BeautifulSoup过滤出csrf-token的值
crsf = soup.find('meta',{'name':'csrf-token'})['content']

d = {
	"authenticity_token": crsf,		#把前面提取到的crsf放在一起提交,必须要有这个
	"back_url": "http://127.0.0.1:81/",  #这是自己搭建的,nginx做的代理,所有这个back_url,可要可不要
	"username": "liqiao",
	"password": "11111111",
	"login": "登录"
}

r = s.post(url, headers=headers, data=d)

#因为登录后的用户名是被<a class="user active" href="...">包含在其中,太长了,所以我只取了一个a
t = re.findall(r'<a(.+?)</a>', r.content.decode('utf-8'))
print(t[0])	#打印登录后的用户名,判断是否登录成功

三、cookie

待补充

关于Python 文件中if name == 'main'的意思

当.py文件被直接运行时,if name == 'main'之下的代码块将被运行;当.py文件以模块形式被导入时,if name == 'main'之下的代码块不被运行。

示例:只有直接执行以下内容的py文件时才会打印“Hello, world!”

def print_info(info):
	print(info)

if __name__ == '__main__':
	print_info("Hello, world!")

最后更新于