1.函数定义
函数名:一般小写字母加下划线
变量名:小写
常量名:大写
类名:首字母大写 驼峰命名法
def 函数名(参数):
#内部代码
return 表达式
def get_resonse(a, b):
pass
return xxx
参数类型和参数的传递:
实参
形参
get_resonse(x, y)
位置参数
默认参数
动态参数
def power(x, n=2):
pass
def foo(x, y , z=10, *args, **kwargs)
pass
power(10)
power(10, 4)
顺序执行
条件判断
if 表达式:
pass
elif 表达式:
pass
elif 表达式:
pass
else:
pass
while中加判断条件
for i in list:
if 表达式:
pass
2. 文件读写
文件读写:打开文件 操作文件 关闭文件名
2.1 open 方法和with上下文管理器
f = open(filename, mode)
f = open("/tmp/test.txt", "w")
f.write("i love python")
f.close
with open("/tmp/test.txt", "w") as f
f.write("i love python")
打开多个文件
with open("/tmp/test1.txt") as f1, open ("/tmp/test2.txt", "w") as f2
s=f1.read()
f2.write(s)
2.2 文件对象操作:
f.read(size) 读取一定大小数据
f.readline() 读行
f.readlinnes() 读取文件所有的行,保存在列表中
f.write() 将数据写入文件
3.面向对象
面向对象编程:将函数和变量封装成类,类和类的实例
- 导入各种外部库
- 设计各种全局变量
- 决定你要的类
- 给每个类提供完整的一组操作
- 明确地使用继承来表现不同类之间的共同点
- 根据需要,决定是否写一个main函数作为程序入口
class Student(object)
def __init__(self, name, age):
self.name = name
self.age = age
def print_age(self)
print('%s: %s' % (self.name, self.age))
a= Student("zhanghai", 18)
a.print_age()
类是抽象的模板,有相同属性和方法的对象的集合
3.1类的定义
class 类名(父类列表):
pass
init的方法就是类的实例化方法用来创建一个类的实例
类的使用:创建实例,调用实例
变量:类名或者实例名加变量名调用
方法:实例加函数名() 或者 类名加函数名()调用
类变量:
实例变量和类变量
实例名.实例变量
类名.类变量
3.2 类的方法分类
类的方法:实例方法、静态方法、类方法
class Get_response:
def __init__(self, name):
self.name = name
def ord_func(self):
"""定义实例方法,至少有一个self参数 """
print('实例方法')
@classmethod
def class_func(cls):
""" 定义类方法,至少有一个cls参数 """
print('类方法')
@staticmethod
def static_func():
""" 定义静态方法 ,无默认参数"""
print('静态方法')
调用实例方法
f = Get_response("Jack")
f.ord_func()
Foo.ord_func(f) # 请注意这种调用方式,虽然可行,但建议不要这么做!
调用类方法
Foo.class_func()
f.class_func() # 请注意这种调用方式,虽然可行,但建议不要这么做!
调用静态方法
Foo.static_func()
f.static_func() # 请注意这种调用方式,虽然可行,但建议不要这么做!
成员保护和访问限制:
如果要让内部成员不被外部访问,可以在成员的名字前加上两个下划线__,这个成员就变成了一个私有成员(private)。私有成员只能在类的内部访问,外部无法访问。
在类的内部创建外部可以访问的get和set方法!
class School:
cla***oom = 10
def __init__(self, name, age):
self.__name = name
self.__age = age
def print_age(self):
print('%s: %s' % (self.__name, self.__age))
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_name(self, name):
self.__name = name
def set_age(self, age):
self.__age = age
obj = People("jack", 18)
obj.get_name()
obj.set_name("tom")
类的成员与下划线总结:
_name、_name_、_name__:建议性的私有成员,不要在外部访问。
__name、 __name_ :强制的私有成员,但是你依然可以蛮横地在外部危险访问。
__name__:特殊成员,与私有性质无关,例如__doc__。
name_、name__:没有任何特殊性,普通的标识符,但最好不要这么起名。
4. 异常处理
4.1 捕获异常语法
try:
pass
except [Except Type]:
pass
else:
pass
finally:
pass
表示如果 try 中的代码没有引发异常,则会执行 else。
表示无论是否异常,都会执行 finally。
常见异常类型
异常类型 用途
SyntaxError 语法错误
IndentationError 缩进错误
TypeError 对象类型与要求不符合
ImportError 模块或包导入错误;一般路径或名称错误
KeyError 字典里面不存在的键
NameError 变量不存在
IndexError 下标超出序列范围
IOError 输入/输出异常;一般是无法打开文件
AttributeError 对象里没有属性
KeyboardInterrupt 键盘接受到 Ctrl+C
Exception 通用的异常类型;一般会捕捉所有异常
s1 = 'hello'
try:
int(s1)
except Exception as e:
print('错误')
5. 模块和包
在Python中,一个.py文件就是一个文件
只有包含init.py文件的目录才会被认为是一个包
包、模块、类、函数、代码块
5.1模块的导入和使用
import xx.xx
导入模块的所有内容:最顶层的包名.次一级包名.(所有级别的包名).模块名.类名.函数名
使用方式:module.xxx
from xx.xx import xx
导入指定部分
使用方式:xx
from xx.xx import xx as rename
重命名,避免冲突
from xx.xx import *
将对象的全部内容导入
模块搜索路径
Python根据sys.path的设置,按顺序搜索模块。
通过sys.path.append('路径')的方法为sys.path路径列表添加你想要的路径。
import sys
import os
new_path = os.path.abspath('../')
sys.path.append(new_path)
os模块
os模块的主要功能:系统相关、目录及文件操作、执行命令和管理进程
(1) 目录及文件操作
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
os.mkdir('dirname') 生成单级目录
os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除并报错
os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件
os.remove('filename') 删除一个文件
os.rename("oldname","new") 重命名文件/目录
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如果path以/或\结尾,那么就会返回空值。
os.path.exists(path或者file) 如果path存在,返回True;如果path不存在,返回False
(2) 执行命令
os.system(command) #运行操作系统命令,直接显示结果。但返回值是0或-1,不能获得显示在屏幕上的数据。这个方法是阻塞当前主进程执行的,只有该命令执行完毕,主进程才会继续执行。
os.system("cat /opt/test.txt")
os.popen(command)也可以运行操作系统命令,并返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。这个方法是后台执行,不影响后续脚本运行。
output = os.popen('ifconfig')
print(output.read())
command模块
commands 模块是 Python 的内置模块,它主要有三个函数:
函数 说明
getoutput(cmd) Return output (stdout or stderr) of executing cmd in a shell.
getstatus(file) Return output of “ls -ld file” in a string.
getstatusoutput(cmd) Return (status, output) of executing cmd in a shell.
(1) commands.getoutput(cmd) 返回Shell命令的输出内容:
import commands
commands.getoutput("pwd")
(2) commands.getstatusoutput(cmd) 返回一个元组(status,output),status 代表的 shell 命令的返回状态,如果成功的话是 0;output 是 shell 的返回的结果:
commands.getstatusoutput("pwd")
(0, '/root')
subprocess
subprocess模块执行操作系统级别的命令
(1) subprocess.call("cat /opt/test.txt", shell=True) 类似os.system(cmd),直接返回结果
(2) subprocess.run()方法返回的不是我们想要的执行结果或相关信息,而是一个CompletedProcess类型对象。
语法: subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None)
(3) subprocess.Popen()返回值是一个Popen对象,Popen对象的stdin、stdout和stderr是三个文件句柄,可以像文件那样进行读写操作。
subprocess.Popen("dir", shell=True)
a = subprocess.Popen("cat /opt/test.txt", shell=True, stdout=subprocess.PIPE)
print a.stdout.read()
s = subprocess.Popen("ipconfig", stdout=subprocess.PIPE, shell=True)
print(s.stdout.read().decode("GBK"))
(4) 要实现前面的'python'命令功能,可以按下面的例子操作:
import subprocess
s = subprocess.Popen("python", stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
s.stdin.write(b"import os\n")
s.stdin.write(b"print(os.environ)")
s.stdin.close()
out = s.stdout.read().decode("GBK")
s.stdout.close()
print(out)
通过s.stdin.write()可以输入数据,而s.stdout.read()则能输出数据。
json模块
json模块:json格式和python格式转换
json的数据要求用双引号将字符串引起来,并且不能有多余的逗号。
要转化成json就'dump',要从json转化成Python就'load';要根据字符串转化就加's',要从文件进行转化就不加's'。
json.dump(obj, fp) 将python数据类型转换并保存到json格式的文件内。
json.dumps(obj) 将python数据类型转换为json格式的字符串。
json.load(fp) 从json格式的文件中读取数据并转换为python的类型。
json.loads(s) 将json格式的字符串转换为python的类型。
对文件的读写:
>>>import json
>>>dic = {"k1":"v1","k2":123}
>>>f = json.dump(dic, open("/opt/test.txt","w"))
>>>obj = json.load(open("/opt/test.txt")) # 重新load回来
>>>obj
{'k1': 'v1', 'k2': 123}
time模块
分类是时间戳、格式化时间字符串和结构化时间
时间戳time.time()
结构化时间:
time.strftime('%Y-%m-%d %H:%M:%S')
'2017-09-26 10:04:28'
time模块主要方法
- time.sleep(t) 用来睡眠或者暂停程序t秒,t可以是浮点数或整数。
- time.time()返回当前系统时间戳。该方法经常用于计算程序运行时间
import time
def func():
time.sleep(1.14)
pass
t1 = time.time()
func()
t2 = time.time()
print(t2 - t1)
sys模块
sys模块主要是针对与Python解释器相关的变量和方法
sys.argv 获取命令行参数列表,第一个元素是程序本身
sys.exit(n) 退出Python程序,exit(0)表示正常退出。当参数非0时,会引发一个SystemExit异常,可以在程序中捕获该异常
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.stdin 输入相关
sys.stdout 输出相关
sys.stderr 错误相关