Python高级教程

Class(类)
  • 构造类,例:
#创建dog类
class dog(object):
    def __init__(self,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')

#使用类实例化对象
Dog=dog('wangchai',2)       #Dog为对象名,dog为类名
#访问对象的属性和方法
print(Dog.name) #访问属性
Dog.sit()       #访问方法
Dog.roll_over() #访问方法



#构造函数
class cat(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
        print("这里是构造函数")
    def __del__(self):      #析构函数,释放函数(del)自动调用
        print('这里是析构函数')
        print(self.name.title()+'  is now sitting')
    def __str__(self):
        return '这里是__str__函数'
    def roll_over(self):
        print(self.name.title()+'  rolled')
Cat=cat('dudu',1)
print(Cat)
print("**************")
print(Cat.age)
print('**************')
Cat.roll_over()
print('**************')
del Cat
print('**************')
  • 重写__repr__与__str__函数
#优点:
class cat(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):                  #在调用print打印对象是自动调用的
       return '这里是__str__函数,person:%s,%d'%(self.name,self.age)
    #def __repr__(self):                   #一般在黑屏终端使用
    #    return'这里是__repr__函数,person:%s,%d' % (self.name, self.age)
obj=cat('mike',2)
print(obj)
  • 访问限制
#
class money(object):
    def __init__(self,money):
        self.__money=money        #属性__money不能直接访问
    def getMoney(self):             #取值
            return self.__money
    def setMoney(self,money):       #赋值+
            #数据过滤
            if money<0:
                money=0
            self.__money=money
s=money(1)
#print(s.__money)    #error
s.setMoney(10000)
a=s.getMoney()
print(a)

  • 单继承
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('this car has '+ str(self.odometer_reading)+'miles on it.')
    def upate_odometer(self,mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer")
    def fill_gas_tank(self):
        print("This car has a gas tank")
    def increment_odometer(self,miles):
        self.odometer_reading += miles



class ElectricCar(Car):                       #圆括号中必须指定父类的名称,子类继承了其父类的所有属性和方法
    def __init__(self,make,model,year):
#初始化父类的属性
        super().__init__(make,model,year) #在pyton 2 中super()圆括号中应加上类名和self
        #添加新属性
        self.battery_size = 70
    #添加方法
    def describe_battery(self):
        #打印一条描述电瓶容量的信息
        print("This car has a "+str(self.battery_size)+"-kwh battery.")
    #重写父类的方法
    #父类中有"fill_gas_tank"方法,但是电动汽车没有油箱,所以重写
    def fill_gas_tank(self):
        print("This car doesn't need a gas tank")


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

print('*******************')
#将实例用作属性
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()
My_tesla=ElectricCar('tesla','model s',2017)
My_tesla.battery.describe_battery()     #调用实例中的方法
  • 多继承
#一个子类继承多个父类,子类继承父类的所有功能

#对象属性和类属性
class Person(object):
    name="person"   #类属性
    #def __init__(self,name):
        #self.name=name  #对象属性

p=Person()
print(p.name)

class PERSON(object):
    name="person"   #类属性
    def __init__(self,name):
        self.name=name  #对象属性,且对象属性的优先级比类属性高
s=PERSON('fangwei')
print(s.name)
  • 动态给实例添加属性和方法并使用
from types import MethodType

#创建一个类
class car(object):
    pass


C=car()
#添加属性
C.name="tesla"
car.whoMade='Tom'
#添加方法
def run(self):
    print(C.name+'  Run!')
#C.run=MethodType(run,C)    #其他实例调用不了
car.run=MethodType(run,car) #给类绑定方法后,所有实例均可调用

print(C.name)
print(C.whoMade)
C.run()

Z=car()
Z.run()

print('*******************')

#定义类的时候,定义一个特殊的属性(__slots__),可以限制动态添加的属性
class Student(object):
    __slots__=('name','age')
s=Student()
s.name='Michal'
s.age=19
print(s.name)
print(s.age)
#s.score=100     #不是指定的属性
#print(s.score)

#@property

class person(object):
    def __init__(self,age):
        #属性.
        # 直接对外暴露
        self.age=age
修饰器
def func():
    print("hello world!")

def deco(func): #定义一个装饰器
    def inner():
        print("********")
        func()
    return inner
f=deco(func)    #f是装饰以后的函数
f()

print('*****************************')
#带有参数的修饰器
#方法一
def say(age):
    print("fang is %d years old"%age)
def deco(func):
    def inner(age):
        if age<0:
            age=0
        func(age)
    return inner
say=deco(say)
say(19)

#方法二
@deco
def say(age):
    print("fang is %d years old"%age)
say(18)


#带有不定参数的修饰器
def deco(func):
    def inner(*arcg,**kwargs):
        print('***********')
        func(*arcg,**kwargs)
    return inner
@deco
def say(name,age):
    print("my name is %s,i am %d years old"%name%age)

say('fang',19)

函数
add_args(arg2='i jie',arg1='fang we')

#默认参数
def describle_pet(pet_name,animal_type='dog'):
    print('my '+animal_type+' name is '+pet_name)
describle_pet('kiki')
describle_pet('zaocai','cat')

#不定长参数
def make_pizza(*toppings): #*创建一个空元组,并将函数收到的所有实参封装到这个元祖中
    print(toppings)
make_pizza('cheese')#返回一个元组
make_pizza('mushrooms','green peppers','cheese')

def make_pizza2(size,*toppings):
    print('Making a '+str(size)+' pizza with the folling topping:' )
    for topping in toppings:
        print('-'+topping)
make_pizza2(12,'mushrooms','green peppers','cheese')

#任意数量的关键字实参
def func(**k):   # ** 创建一个空字典,用于储存(键-值)对
    print(k)
    print(type(k))
dict=func(num1=19,str1='name',num2=13,str2='cool')

#匿名函数
sum=lambda num1,num2,num3:(num1+num2)*num3
print(sum(2,2,3))

模块
  • 时间模块
import time

a=time.time()   ##返回当前时间的时间戳,浮点数形式,不需要参数
print(a)
print(type(a))

print('************')


b=time.localtime()   #将时间戳转为本地时间元组
print(b)
print(type(b))

print('************')

c=time.localtime(a)
print(c)

print('************')

d=time.gmtime(a)    #将时间戳转化为UTC时间元组
print(d)

print('************')

e=time.mktime(b)    #将本地时间转化为时间戳
print(e)

print('************')

f=time.asctime(b)   #将时间元组转化为字符串
print(f)

print('************')

g=time.ctime(a) #将时间戳转为字符串
print(g)

print('************')

h=time.strftime('%Y-%m-%d  %H:%M:%S',b) #将时间元组转化为给定格式的字符串,参数1为指定格式,参数2为时间元组
print(h)

print('************')

i=time.strptime(h,'%Y-%m-%d %X')    #将时间字符串转化为时间元组
print(i)

print('************')

time.sleep(4)
print('hello')

t=time.clock()
print(t)
time.sleep(5)
t2=time.clock()
print(t2)

  • datetime模块
import datetime
t1=datetime.datetime.now()  #获取当前时间
print(t1)
print(type(t1))

t2=datetime.datetime(1999,1,26,7,30)    #获取指定时间
print(t2)

t3=t1.strftime('%Y-%m-%d %X')   #将时间转化为格式化字符串
print(t3)
print(type(t3))

t4=datetime.datetime.strptime(t3,'%Y-%m-%d %X') #将时间格式化字符串转为datetime对象,转换的格式要与字符串一致
print(t4)
print(type(t4))

#print(t3-t2)    #TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'
print(t4-t2)    #两个时间的加减

  • 日历模块,calendar
import calendar

print(calendar.month(2018,10))  #返回指定某年某月的日历

print(calendar.calendar(2018))  #返回指定年的日历

print(calendar.isleap(2018))    #判断是否是闰年,若是则返回true,否则返回false

print(calendar.monthrange(2018,10)) #返回某个月的第一天是星期几的日期码和这个月的天数

print(calendar.monthcalendar(2018,10))  #返回一整数的单层嵌套列表,每个子列表包含了一个星期的整数,范围外的日子为零,

  • 自定义模块
import MyModule
print(MyModule.func())

from MyModule import func   #从模块中引入某个指定部分
func()

from MyModule import*   #将一个模块中的所有的内容全部导入当前命名空间
func()
func1()


#当文件是被调用时,__name__的值为模块名
#当文件被执行时,__name__的值为‘__main__’
if  __name__ =="__main__":
    print("this is main of module ")

print("\n**************\n")

#包
#引入包和模块
from newfile import daily,weekly
import newfile

#调用包中的模块
newfile.daily

递归
#函数直接或间接调用了这个函数本身
#直接调用自己
'''
def func():
    print("form func")
    func()

func()

#间接调用自己
def foo():
    print('form foo')
    bar()
def bar():
    print('form bar')
    foo()
foo()
'''
#递归的实现
def age(n):
    if n==0:
        return 18
    print(n)
    return age(n-1)
age(18)
读写文件
  • path=r"E:\pycharm project/fang.txt", 这里是文件绝对路径
  • 读文件
#读文件
file=open(path,'r')
#str=file.read()
#print(str)

str2=file.read(5)   #读取指定字符数
print(str2)

str3=file.readline()
print(str3)
str4=file.readline()    #读取一整行
print(str4)

str5=file.readline(3)    #可读取一行中3个字符
print(str5)

file.seek(0)    #修改描述符的位置,0为修改后的位置
list1=file.readlines()
print(list1)

file.close()
#str6=file.read()    #报错,文件已关闭

  • 写文件
file1=open(path,'w')
file1.write('Already written')
file1.write('\nfangweije is a nice man!')

file1.close()

  • list,tuple,dict,set的文件操作
list=[3,'w',3.5,'apple']
#dict={'apple':'red','orange':'orange'}
import pickle
file2=open(path,'wb')
pickle.dump(list,file2)
#pickle.dump(dict,file2)
file2.close()


file3=open(path,'rb')
templist=pickle.load(file3)
print(templist)
file3.close()

  • os模块
import os
print(os.name)  #windows输出’nt‘,linux.unix输出’posix‘
print(os.environ)   #获取操作系统中的全部环境变量
print(os.environ.get('APPDATA'))    #获取指定环境变量

print(os.curdir)    #获取当前目录
print(os.getcwd())  #获取当前工作目录,即当前Python脚本所在的目录
print(os.listdir('E:\pycharm project\.idea'))
#os.mkdir('newFile') #在当前的目录下创建新目录
#os.rmdir('newFile')     #删除指定目录
print(os.stat("newFile"));  #获取文件属性
os.rename("newFile","newfile")  #重命名
#os.remove("fangweijie.py")  #删除普通文件

print("****************")
str=os.path.abspath('newfile')  #查看当前的绝对路径
print(str)
print(type(str))

path1=os.path.join(str,'fang.py')   #拼接路径
print(path1)

tuple=os.path.split(path1)    #拆分路径,返回一个路径
print(tuple)

print(os.path.splitext(path1))  #获取拓展名,若无拓展名,则返回none

bool1=os.path.isdir('newfile')  #判断是否是目录
print(bool1)
bool2=os.path.isdir('fang.py')
print(bool2)

print(os.path.isfile('dict.py'))    #判断文件是否存在

print(os.path.exists('newfile'))    #判断目录是否存在

num=os.path.getsize(path1)  #获取文件大小
print(num)

str2=os.path.dirname(path1)   #获取文件所处的目录,要是绝对路径
print(type(str2))
print(str2)

str3=os.path.basename(path1)    #获取当前文件名
print(str3)

  • 编码解码
path='E:\pycharm project\.idea/newfile/fang.py'
str='fangweije is a great man'
with open(path,'wb') as file:
    file.write(str.encode('gbk'))
with open(path,'rb') as file2:
    data=file2.read()
    print(data)
    print(data.decode('gbk'))
异常处理
#使用try和except处理错误

short_list=[1,2,3]
pos=6
try:
    print(short_list[pos])
except:                     #try中语句被执行,若存在错误,就会抛出异常,然后执行except中的代码
    print('list index out of range')

#有时需要除了异常外的其他的异常细节

short_list=[1,2,3]
pos=6
try:
    print(short_list[pos])
except IndexError as err:   #将一个IndexError异常赋给变量err,其中IndexError就是错误类型
    print('Bad index:',pos)
    print('cause of error:',err)
except Exception as other:  #把其他异常赋给other
    print('something else broke:',other)

#编写自己的异常
#即自己定义异常类型
模拟堆栈和队列
#模拟栈结构
stacks=[]

#压栈
stacks.append('a')  #一次只能存储一个数据
stacks.append('b')
stacks.append(24)
print(stacks)

#出栈
res=stacks.pop()    #删除列表中的一个数,默认为最后一个元素,并返回被删除的元素
stacks.pop(0)   #也可以指定下标
print(res)
print(stacks)

#模拟队列结构

#创建队列
import queue
device_queue=queue.deque()
print(device_queue)

#入队
device_queue.append('apple')
device_queue.append('a')
device_queue.append(2.1)
device_queue.append(5)
print(device_queue)

#出队
res1=device_queue.popleft() #删除列表最左边的元素,并返回被删除的元素
print(res1)
print(device_queue)

遍历目录
def getalldir(path):
    stack=[]    #创建一个文件目录列表
    stack.append(path)  #往列表中存入一个目录的绝对路径
    while len(stack)!=0:    #若列表为空,则跳出循环
    #while stack != none:
        dirPath=stack.pop() #从stack中取出数据,默认列表中最后一个元素
       # print(dirPath)
        fileList=os.listdir(dirPath)    #目录下所有文件
        #print(fileList)
        for fileName in fileList:   
            fileAbsPath=os.path.join(dirPath,fileName)
            if os.path.isdir(fileAbsPath):  #判断该绝对路径是否是目录
                print('目录:'+fileName)
                stack.append(fileAbsPath)   #若是目录,则将该路径赋到列表stack中
            else:
                print('普通文件:'+fileName)

getalldir(path1)

群发短信
import http.client
import urllib

host  = "106.ihuyi.com"
sms_send_uri = "/webservice/sms.php?method=Submit"

#用户名是登录用户中心->验证码短信->产品总览->APIID
account  = "C00148246"
#密码 查看密码请登录用户中心->验证码短信->产品总览->APIKEY
password = "fdd5533840bbfb6ee18ea4cc7751b5d6"

def send_sms(text, mobile):
    params = urllib.parse.urlencode({'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' })
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    conn = http.client.HTTPConnection(host, port=80, timeout=30)
    conn.request("POST", sms_send_uri, params, headers)
    response = conn.getresponse()
    response_str = response.read()
    conn.close()
    return response_str

if __name__ == '__main__':

    mobile = "17320015926"
    text = "您的验证码是:121254。请不要把验证码泄露给其他人。"

    print(send_sms(text, mobile))
    

turtle

  • turtle(海龟)是Python重要的标准库之一,它能够进行基本的图形制。turtle图形绘制的概念诞生于1969年,成功应用于LOGO编程语言。turtle库绘制图形有一个基本框架:一个小海龟在坐标系中爬行,其爬行轨迹形了绘制图形。刚开始绘制时,小海龟位于画布正中央,此处坐标为(0,0),前进方向为水平右方。在Python3系列版本安装目录的Lib文件夹下可以找到turtle.py文件。
import turtle
import time
#设置画布的大小
turtle.screensize(100,200,'red')
turtle.setup(0.6,0.6)
#画笔的状态
turtle.pensize()    #画笔的宽度
turtle.pencolor('green')   #画笔的颜色
turtle.speed(100000000000)  #画笔移动的速度
#画笔运动命令
turtle.forward(200) #向当前方向移动某个长度
turtle.right(90)    #顺时针旋转某个角度
turtle.backward(100)    #向当前方向的反方向移动
turtle.left(270)    #逆时针旋转
turtle.forward(200)
turtle.left(90)
turtle.forward(100)

turtle.penup()  #将画笔提起
turtle.goto(-200,100)    #移动到某个坐标,默认移动式也画图
turtle.pendown()    #将画笔落下
turtle.color('black')
turtle.pensize(5)
turtle.circle(50)   #画圆,并指定半径
turtle.setheading(90)   #设置当前画笔朝向的角度

#画笔控制命令

turtle.fillcolor('blue')   #设置填充颜色
turtle.begin_fill()     #开始填充
turtle.goto(-200,-100)
turtle.circle(20)
turtle.end_fill()   #结束填充
print(turtle.filling())     #返回当前是否在填充状态


turtle.color('blue','purple')
turtle.begin_fill()
turtle.penup()
turtle.goto(200,-200)
turtle.pendown()
turtle.forward(200) #向当前方向移动某个长度
turtle.right(90)    #顺时针旋转某个角度
turtle.backward(100)    #向当前方向的反方向移动
turtle.left(270)    #逆时针旋转
turtle.forward(200)
turtle.left(90)
turtle.forward(100)
turtle.end_fill()

turtle.hideturtle() #隐藏画笔
turtle.showturtle() #显示画笔


#全局控制命令
#turtle.undo()   #撤销上一个turtle动作
#turtle.clear() #清空turtle窗口,但turtle的位置和状态不变
turtle.reset() #清空窗口,turtle重置到起始状态


#画出一个五角星
turtle.screensize(200,300,'white')
turtle.pensize(4)
turtle.color('yellow','red')
turtle.begin_fill()
i=0
while i<5:
    turtle.forward(200)
    turtle.right(144)
    i+=1
turtle.end_fill()
turtle.penup()
turtle.goto(-200,-100)
turtle.pendown()
turtle.write('done!')

time.sleep(10)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值