本教程主要为Python3教程,但涉及一些Python2语法,文章中默认为Python3,若为Python2则会有标注。
可变集合(set),不可变集合(frozenset),没有重复和顺序,集合可以相互比较
函数的声明和创建:def语句
def 函数名 (参数列表):
语句 | 函数体
示例:
def my_average(a, b):
return (a+b)/2
class Person{
String name;
int age;
public Person(String n, int a){
this.name=n;
this.age=a;
}
}
python中: class Person:
def __init__(self, name, age):
self.name=name
self.age=age
def say_hi(self):
print('你好,我叫', self.name)
p1=Person('张三', 45)
p1.say_hi()
class Car:
name='aodi'
__price=100
类内函数
c1=Car()
# 则c1不能访问c1.__price,若想访问,则需类内定义函数
# 方法一:
def get_into():
print(Car.__price)
Car.get_into #使用全局调用
# 方法二:
# 调用私有属性:对象._类名__私有属性
c1._Car__price
# 方法三:装饰器@property(属性)
class Person:
def __init__(self, name):
self.__name=name
@property # 提供只读属性
def name(self):
return self.__name
p=Person('Tom')
print(p.name)
# 方法四:getter, setter
class Person:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
@name.getter
def name(self):
return self.__name
p= Person('Tom')
p.name = 'allen'
print(p.name)
# 方法五:人工构造
class Person:
def __init__(self, name):
self.__name=name
def getname(self):
return self.__name
def setname(self, value):
self.__name=value
def delname(self):
del self.__name
name = property(getname, setname, delname, '我是name属性')
p=Person('Tom')
p.name='Allen'
ii. 自定义属性:即增加属性,只能是公开属性 class C1:
pass
o = C1()
o.name = '自定义属性'
print(o.name)
o.__dict__
iii. 自动获取属性 class Person:
def __init__(self):
pass
def __getattribute__(self, name):
return str.upper(object.__getattribute__(self, name))
def __setattribute__(self, name, value):
object.__setattr__(self.name, str.strip(value))
o=Person()
o.firstname='DLUT'
print(o.firstname)
iv. 方法: # 示例方法:def 方法名(self, [参数列表])
class Person:
def say_hi(self, name):
self.name=name
print('我叫', self.name)
p=Person()
p.say_hi('软件学院')
# 静态方法:
@staticmethod
def 方法名称([参数列表])
class Person:
@staticmethod
def show(name):
return name+1
Person.show(1)
# 类方法:
@classmethod
def 方法名称(cls, [参数列表])
class Foo:
classname = 'Foo'
def __init__(self, name):
self.name=name
def f1(self):
print(self.name)
@staticmethod
def f2():
print('static')
@classmethod
def f3(cls):
print(cls.classname)
f = Foo('中')
f.f1()
Foo.f2()
Foo.f3()
v. 私有方法 class Methods:
def publicMethod(self):
print('公有方法')
def __privateMethod(self):
print('私有方法')
def publicMethod2(self):
self.__privateMethod()
m=Methods()
m.publicMethod()
m.__privateMethod() #不能访问
m._Methods__privateMethod()
Methods.publicMethod(m) #需传参,参数需为对象
class Person:
def say_hi(self, name):
print('你好,我叫', self.name)
def say_hi(self, name, age):
print('你好,我叫{0},我的年龄是{1}'.format(name, age))
p=Person()
p.say_hi('tom', 23)
class Foo(object): #object可默认不写
class Persion:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print('你好,我叫{0},年龄{1}'.format(self.name, self.age))
class Student(Person):
def __init__(self, name, age, stu_id):
Person.__init__(self, name, age)
self.stu_id = stu_id
def say_hallo(self):
Person.say_hi(self)
print('我是学生,我的学号是', self.stu_id, sep='')
p1 = Person('张三', 33)
p1.say_hi()
s1 = Student('李四', 19, '20181010')
s1.say_hello()
# 只有一个父类时,可以用super代替父类的类名,super会自动查找
class Student(Person):
def __init__(self, name, age, stu_id):
super(Student, self).__init__(name, age)
self.stu_id = stu_id
def say_hello(self):
super(Student, self).say_hi()
print('我是学生,我的学号是', self.stu_id)
s1 = Student('Allen', 23, '20190101')
s1.say_hello()
class A:
pass
class B(A):
pass
class C(B):
pass
class D(A):
pass
class E(B, D):
pass
D.mro()
E.__mro__
class Dimesion:
def __init__(self, x, y):
self.x = x
self.y = y
def area(self):
pass
class Circle(Dimesion):
def __init__(self, r):
Dimesion.__init__(self, r, 0)
def area(self):
return 3.14*self.x*self.x
class Rectangle(Dimesion):
def __init__(self, w, h):
Dimesion.__init__(self, w, h)
def area(self):
return self.x * self.y
d1 = Circle(2.0)
print(d1.area())
# 调用的是非私有的方法,如果子类方法是私有,则会出现None
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return '{0}, {1}'.format(self.name, self.age)
p = Person('Tom', 23)
print(p)
x = 1
y = 2
print(x+y)
x.__add__(y)
def __add__(self)
return
with open(r'd:\data.txt', 'w', encoding='utf-8') as f: # r代表禁止转移字符
f.write('123\n')
f.write('abc\n')
f.writelines(['456\n', 'def\n'])
with open(r'd:\data.txt', 'r', encoding='utf-8') as f:
for s in f.readlines():
print(s, end=' ')
# 二进制文件的读写
with open(r'path', 'wb') as f:
f.write(b'abc')
with open(r'path', 'rb') as f:
b = f.read()
print(b)
# 随机文件读取,模式改为'w+b'
# 内存文件的操作:在内存中创建临时文件,进行数据的读取和写入,需要用io模块,在模块中,StringIO和GytesIO对象来实现内存操作
from io import StringIO
f = StringIO('hello\nhi\ngoodbye')
for s in f:
print(s)
from io import BytesIO
f = BytesIO()
f.write('abc'.encode('utf-8'))
f.seek(0)
b=f.read()
print(b)
print(f.getvalue())
import sys, gzip
filename = sys.argv[0]
filenamezip = filename + '.gz'
with gzip.open(filenamezip, 'wt') as f:
for s in open(filename, 'r'):
f.write(s)
for s in gzip.open(filenamezip, 'r'):
print(s)
import csv
def readcsv1(csvfilepath):
with open(csvfilepath, newline=' ') as f:
f_csv = csv.reader(f) # 创建csv.reader对象
headers = next(f_csv) # 标题
print(headers)
for row in f_csv:
print(row)
if __name__=='__main__':
readcsv1(r'd:\scores.csv')
# 示例2
import csv
def writecsv1(csvilepath):
headers=['StuID', 'Name', 'Sex', 'Class', 'Math', 'Chinese', 'English']
rows=[('20181010', 'Allen', 'Male', 'Class1', '90', '80', '78'), ('20181011', 'Mary', 'Female', 'Class2', '90', '98', '92')]
with open(csvfilepath, 'w', newline=' ')as f:
f_csv=csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
if __name__='__main__':
writecsv1(r'd:/sc.csv')
import os
filename = r'd: \data1.txt'
isExists = os.path.exists(filename)
if isExists:
os.remove(filename)
print('文件删除成功')
else:
print('要删除的文件不存在')
import os
dirname = r'd:\pythontest'
multipledirname = r'd:\pythontest1\program\test'
isExists = os.path.exists(dirname)
if isExists:
print(dirname, '文件夹已经存在了')
else:
os.mkdir(dirname)
print('成功创建了文件夹', dirname)
isExists = os.path.exists(multipledirname)
if isExists:
print(multipledirname, '文件夹已经存在了')
else:
os.mkdir(multipledirname)
print('成功创建了多级文件夹', multipledirname)
import os
import shutil
dirname = r'd:\pythontest'
# multipledirname = r'd:\pythontest1\program\test'
multipledirname = r'd:\pythontest1'
isExists = os.path.exists(dirname)
if isExists:
os.rmdir(dirname)
print('成功删除文件夹')
else:
print('要删除的文件夹不存在')
isExists = os.path.exists(multipledirname)
if isExists:
# os.rmdir(multipledirname)
shutil.rmtree(multipledirname)
print('成功删除文件夹')
else:
print('要删除的文件夹不存在')
i = 1
for j in range(100):
file_name = base + str(i)
os.mkdir(file_name)
i = i+1
if __name__=='__main__':
genDir()
import os, sys
path1 = r'c:/101test'
path2 = r'd:/bd/train/train/train1/'
def MKDir():
dirs = os.listdir(path1)
for i in dirs:
file_name = path2+str(i)
os.mkdir(file_name)
if __name__=='__main__':
MKDir()
import os
basepath=r'd:/bd/train/train1/'
for line in open(r'c:/102test/ab.txt'):
basename = line.strip() #去掉前后的空格
folder = os.path.join(basepath, basename) # 将列表组成字符串
filename = os.path.join(folder, basename)
os.mkdir(folder)
open(filename, 'w').close()
import pickle
with open(r'd:/pythontest1/dataObj.dat', 'wb') as f:
s1 = 'hello'
s2 = 1+2j
s3 = (1, 2, 3)
s4 = dict(name='Mary', age=19)
pickle.dump(s1, f)
pickle.dump(s2, f)
pickle.dump(s3, f)
pickle.dump(s4, f)
# 反序列化
import pickle
with open(r'd:/python')as f:
o1=pickle.load(f)
o2=pickle.load(f)
o3=pickle.load(f)
o4=pickle.load(f)
print(type(o1), str(o1))
print(type(o2), str(o1))
print(type(o3), str(o1))
print(type(o4), str(o1))
try:
f = open(r'test.txt', 'w')
f.write('This is a test file.')
f1. = open('resxtifile.txt', 'r')
except IOError:
print('Not found the file')
else:
# 没有异常时,执行的语句
print('File writing success!')
finally:
f.close()
class NumberError(Exception):
def __init__(self, data):
Exception.__init__(self, data)
self.data = data
def __str__(self):
return self.data+'非法数值'
def total(data):
total = 0
for i in data:
if i<0: raise NumberError(str(i))
total=total+1
return total
断言是做调试用的
if __debug__:
if not testexpression: raise AssertionError
if __debug__:
if not testexpression: raise AssertionError(data)
# 示例:
a = int(input('请输入整数A'))
b = int(input('请输入整数B'))
assert b!=0, '除数不能为0'
c = a/b
print(c)
'''
1) py.test: 它是一个轻量级的测试框架
pip install -U pytest
运行(在命令行中):
py.test 文件名.py
'''
# 2) 使用Python自带的测试框架unittest
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'Fo0')
if __name__=='__main__':
unittest.main()
# 3) ptest
# Karl大神,可读性非常好
from ptest.decorator import *
from prest.assertion import *
@TestClass()
class TestCase:
@Test()
def test1(self):
actual='foo'
expected='bar'
assert_that(expected).is_equal_to(actual)
# 4) assertpy包
from assertpy import assert_that
def test_something():
assert_that(1+2).is_equal_to(333)
assert_that('foobar').is_length(6).starts_with('foo').ends_with('bar')
if __name__=='__main__':
test_something()
# 5) 17个方法,可以在网上查阅
import pymysql
db=pymysql.connect("localhost", "root", "root", "testdb")
cursor=db.cursor()
cursor.execute("DROP TABLE IF EXISTS employee")
# 使用预处理的方式进行建表
sql="""CREAT TABLE employee(
first_name CHAR(20) NOT NULL,
last_name CHAR(20),
age INT,
sex CHAR(1),
imcome FLOAT)"""
cursor.execute(sql)
db.close()
# 11.csv为csv文件,导入时需要先在数据库创建表
import pymysql
import csv
import codecs
def get_conn():
conn = pymysql.connect(
host='localhost',
port=3306
user='root'
passwd='root'
db='test_csv'
charset='utf8'
)
return conn
def insert(cur, sql, args):
cur.execute(sql, args)
def read_csv_to_mysql(filename):
with codecs.open(filename=filename, mode='r', encoding='utf-8') as f:
reader=csv.reader(f)
head=next(reader)
conn=get_conn()
cur=conn.cursor()
sql='insert into tb_csv values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' # 简写
for item in reader:
if item[1] is None or item[1]=='':
continue
args=tuple(item)
print(args)
insert(sur, aql=sql, args=args)
conn.commit() # 提交和关闭不能忘
cur.close()
conn.close()
if __name__=='__main__':
read_csv_to_mysql(r'd:/11.csv')
import pymysql
import csv
import codecs
def get_conn():
conn = pymysql.connect(
host='localhost',
port=3306
user='root'
passwd='root'
db='test_csv'
charset='utf8'
)
return conn
def query_all(cur, sql, args): # args可以不写
cur.execute(sql, args)
return cur.fechall()
def read_mysql_to_csv(filename):
with codecs.open(filename=filename, mode='w', encoding='utf-8') as f:
write=csv.writer(f, dialect='excle')
conn=get_conn()
cur=cunn.cursor()
sql='select * from tb_csv' # '*' 尽量不要写
results=quer_all(cur=cur, sql=sql, args=None)
for result in results:
print(result)
write-weiterew(result)
if __name__=='__main__':
read_mysql_to_csv(r'd:/22.csv')
# 1) pandas: 数据分析库
# 安装:pip install pandas
import pymysql
# 字典模式
config=dict(host='localhost',
user='root',
password='root',
xursorclass=pymyaql.cursors.DictCursor
)
# 建立连接
conn=pymysql.connect(**config)
# 自动提交
conn.autocommit(1)
# 设置光标
cusor=conn.cursor()
import pandas as pd
df=pd.read_csv(r'd:/33.csv', encoding='gbk', usecols[0, 3, 4, 5, 6, 11], parse_dates=['日期'])
print(df.head())
def make_table_sql(df):
columns=df.columns.tolist()
types=df.ftypes
mak_table=[]
for item in columns:
if 'int' in types[item]:
char=item+' INT'
elif 'float' in types[item]:
char=item+' FLOAT'
elif 'object' in types[item]:
char=item+' VARVHAR(255)'
elif 'datetime' in types[item]:
char=item+' DATETIME'
make_table.append(char)
return ','.join(make_table)
# csv格式输入到mysql中
def csv2mysql(db_name, table_name, df):
# 创建数据库
cursor.execute('CREAT DATABASE IF NOT EXISTS {}'.format(db_name))
# 连接
conn.select_db(db_name)
# 创建表
cursor.execute('CREAT TABLE {}'.format(table_name, make_table_aql(df)))
df['日期']=df['日期'].astype('str')
values=df.values.tolist()
s=','.join(['%s' for _ in range(len(df.columns))])
cursor.excutemany('INSERT INTO {} VALUES([])'.format(table_name, s), values)
cursor.close()
conn.close()
if __name__=='__main__':
csv2mysql('stock', 'test1', df)
# 2) sqlalchemy
import pandas as pd from sqlalchemy
import create_engine from datetime
import datetime from sqlalchemy.types
import NVARCHAR, Float, Integer
engine=create_engine("mysql+pymysql://root:[email protected]:3306/stock?charset=utf-8", max_overflow=5) # 密码相同可不写,最大连接数为5
con=engine.connect()
df=pd.read_csv(r'd:/33.csv', encoding='gbk', usecols=[0, 3, 4, 5, 6, 11],parse_date='日期')
def map_types(df):
dtypedict={}
for I, j in zip(df.columns, df,dtypes):
if "object" in str(j):
dtypedict.update({i:NVARCHAR(length=255)})