python入门
基于python3.8.2版本
一、语法
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'a test module' __author__ = 'authorName' def fn(x): return x*x r = map(fn, [1,2,3,4,5,6]) print(list(r)) from functools import reduce def fn2(x, y): return x*10 + y ss = reduce(fn2, [1,2,3,4,5]) print(ss) a = ['adam', 'LISA', 'barT'] def f1(x): return x[0].upper() + x[1:].lower() aa = map(f1, a) print(list(aa)) def f2(x, y): return x * y ff2 = reduce(f2, [1,2,3]) ff3 = reduce(lambda x,y:x*10+y ,[1,2,3]) print(ff2,':',ff3) def ff4(x,y): return x/10 + y ff4a=reduce(ff4, [1,2,3]) print('ff4a:',ff4a) #字符串转浮点 def strtofloat(s): i = s.find('.') digist = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9} def f1(x,y): return x*10+y def f2(n): return digist[n] def f3(x,y): return x/10+y return reduce(f1, map(f2,s[:i])) + reduce(f3, map(f2, s[:i:-1]))/10 print('123.456:', strtofloat('123.456')) def f1(x): return x%2==0 xx = filter(f1, [1,2,3,4,5,6]) print(list(xx)) aa=sorted(['a','AA','sdf'],key=str.lower,reverse=True) print(aa) L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def sortByName(x): return x[0] def sortByCords(x): return x[1] ll = sorted(L,key=sortByName) ss = sorted(L, key=sortByCords, reverse=True) print("ll by name:", ll,";ss:",ss) def fn(*args): return args def addCount(): n=0 def add(): nonlocal n n = n + 1 return n return add ff=addCount() print('ff:',ff(),ff(),ff()) def addCount(): n=[0] def add(): n[0] = n[0] + 1 return n[0] return add ff=addCount() print('ff:',ff(),ff(),ff()) def addCount(): global n n=0 def add(): global n n = n + 1 return n return add ff=addCount() print('ff:',ff(),ff(),ff()) xx = map(lambda x: x*x, [1,2,3]) print('xx:',list(xx)) f = lambda x:x+x print('ff:',f(1)) L = list(filter(lambda n: n%2==1, range(1, 20))) print(L) print(addCount.__name__) int('123', base=8) #装饰器decorator def log(func): def wrapper(*args, **kw): print('log call %s()' %func.__name__) return func(*args, **kw) return wrapper @log def now(): print("exec now") now() import sys if __name__ == "__main__": print(sys.argv, __doc__) class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print("%s: %s" %(self.__name, self.__score)) def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self, score): self.__score = score aa = Student('aa',100) aa.print_score() print('get_name: %s' % aa.get_name()) class Animal(object): count = 0 __slots__=('name','age') def __init__(self): Animal.count = Animal.count + 1 print('init Animal') def run(self): print('animal running...') class Dog(Animal): def __init__(self): print('init Dog') animal = Animal() animal.run() dog = Dog() dog.run() print(isinstance(dog, Dog)) print(isinstance(dog, Animal)) dir(dog) #获得一个对象的所有属性和方法 hasattr(dog,'run') getattr(dog,'aa','test') print(Animal.count) class Student(object): @property #Python内置的@property装饰器就是负责把一个方法变成属性调用的,把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@birth.setter,负责把一个setter方法变成属性赋值 def birth(self): return self.__birth @birth.setter def birth(self,value): self.__birth = value @property def age(self): return self.__birth -10 a = Student() a.birth=100 print('a.birth: %s' %a.birth) # a.age=100 print('a.age: %s' %a.age) class Screen(object): def __init__(self, width, height): self.__width = width self.__height = height @property def width(self): return self.__width @width.setter def width(self, width): self.__width = width @property def height(self): return self.__height @width.setter def height(self, height): self.__height = height @property def resolution(self): return self.__width * self.__height screen = Screen(100,200) print('width:%s' %screen.width) screen.width=300 print('width:%s' %screen.width) print('resolution:%s' %screen.resolution) class RunMixin(object): def runx(self): print(' xxx running...') class Test(Animal, RunMixin): #多重继承,多个类存在同一个方法,会取主继承类的方法 def aa(self): print('running...') test = Test() test.runx() from enum import Enum, unique @unique class Weekday(Enum): Sun = 0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 print('Weekday.Sun %s' %Weekday.Sun) def fn(self, name='world'): print('Hello, %s.' %name) Hello = type('Hello', (object,), dict(hello=fn)) #动态创建一个class对象,type()函数依次传入3个参数:1.class的名称;2.继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;3.class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。 h = Hello() h.hello() import logging try: print('try...') r = 10 / int('a') print('result:',r) except ValueError as e: print('ValueError',e) logging.exception(e) except ZeroDivisionError as e: print('ZeroDivisionError', e) finally: print('finally') print('end') def foo(s): n = int(s) if n==0: raise ValueError('invalid value:%s' %s) #抛出ValueError return 10/n def bar(): try: foo(0) except ValueError as e: print('ValueError') raise #raise语句如果不带参数,就会把当前错误原样抛出,继续往上抛,让顶层调用者去处理 bar()
二、语法
age = 20 if age >= 18: print("your age is :", age) print("adult") elif age < 10: print('yong') else: print('other') arr = ['a', 'b', 'c'] for i in arr: print("arr item:", i) sum = 0 for i in range(101): sum = sum + i print("range item:", sum) n = 30 i = 0 while i < 10: i = i + 1 print("i:",i) birther = 2000#input("your brith:") s = int(birther) if s > 2000: print('20后') print('test') else: print('other') def absfn(x): if (x > 3): return x else: return x+x print("absfn:",absfn(3)) from collections import Iterable print('iterable:', isinstance('abc', Iterable)) import os dirtest = [d for d in os.listdir('../')] print('dirtest:', dirtest) l = ['AB','BC','EF'] ll = [s.lower() for s in l] print(ll) L = ['Hello', 'World', 18, 'Apple', None] LL = [l.lower() if isinstance(l, str) else l for l in L] LLL= [l.lower() for l in L if isinstance(l,str)] print('LL:', LL,';LLL:', LLL)
三、语法
import re test = re.match(r'^(\d{2})-(\d{3})', '12-345') print(test,test.group(0),test.group(1),test.group(2)) print(test.groups()) from datetime import datetime print(datetime.now()) print(datetime.now().strftime('%a, %b %d %H:%M')) #datetime转str dt = datetime(2020,3,1,12,10) print(dt.timestamp()) #单位秒,timestamp是一个浮点数,它没有时区的概念,而datetime是有时区的 print(datetime.fromtimestamp(dt.timestamp())) #转换为datetime cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') #字符串转datetime print(cday)
四、语法
f = open('./test.py', 'r', encoding='UTF-8') x=f.read(); f.close(); print(x) f = open('./test.py', 'a', encoding='UTF-8') f.write('#test test test open ') f.close(); f = open('./test.py', 'r', encoding='UTF-8', errors='ignore') x=f.read() f.close() print('write:%s' %x) with open('./test.py', 'r', encoding='UTF-8') as f: print(f.read()) with open(r'D:\xxx\python\test.py', 'r', encoding='UTF-8') as f: #在路径前面加r,即保持字符原始值的意思。 print(f.read()) from io import StringIO f = StringIO() f.write('hello') f.write(' ') f.write('wrold!') print(f.getvalue()) import os os.environ.get('PATH') #要获取某个环境变量的值 s = os.path.abspath('.') # 查看当前目录的绝对路径 testdir = os.path.join(s, 'testdir') #使用join创建新目录路径 if os.path.exists(testdir) == False: #存在文件或目录 os.mkdir(testdir) #创建新目录 ll=[x for x in os.listdir('.') if os.path.isdir(x)] #列出当前目录下的所有目录 print(ll) import json d = dict(name='foo',age=123) dstr= json.dumps(d)#json转字符串 print(dstr) dd = json.loads(dstr) #字符串转json print(dd) import re test = '_abc' if re.match(r'^\d', test): print('matched') else: print('not matched') print(re.split(r'\s+', 'a b c d e')) from collections import namedtuple Point = namedtuple("Point",['x','y']) p = Point(0,1) print(p.x, p.y) import hashlib md5=hashlib.md5() md5.update('this is md5 test '.encode('UTF-8')) md5.update('add'.encode('UTF-8')) #如果数据量很大,可以分块多次调用update(),最后计算的结果和一次调用所有数据是一样的 print(md5.hexdigest()) def get_md5(s): return hashlib.md5(s.encode('UTF-8')).hexdigest() print(get_md5('test'), get_md5('this is md5 test add')) import hmac message=b'hello' key=b'secret' h = hmac.new(key, message, digestmod='MD5') #支持MD5和SHA-1 print(h.hexdigest()) from urllib import request, parse with request.urlopen('https://www.qq.com/') as f: data = f.read() print('status:',f.status, f.reason) for k, v in f.getheaders(): print('%s: %s' %(k, v)) # print('data:',data.decode('UTF-8')) req = request.Request('https://www.qq.com/') req.add_header('user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36') #添加header with request.urlopen(req) as f: data = f.read() print('status:',f.status, f.reason) for k, v in f.getheaders(): print('%s: %s' %(k, v)) print('data:',data.decode('UTF-8')) #postData = parse.urlencode([ # ('name', 'test'), # ('age', 20) #]) #req = request.Request('https://www.qq.com/') #req.add_header('Origin', 'https://www.qq.com') #with request.urlopen(req, data=postData.encode('UTF-8')) as f: #post请求,只需要把参数data以bytes形式传入 # data = f.read() # print('status:',f.status, f.reason) # for k, v in f.getheaders(): # print('%s: %s' %(k, v)) # print('data:',data.decode('UTF-8')) from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def __init__(self): super().__init__() self.content = "" def handle_starttag(self, tag, attrs): print('handle_starttag:','<%s>' % tag) if tag == 'meta' and ('name', 'description') in attrs: print('attrs:',attrs[1][0], attrs[1][1]) self.content = attrs[1][1] def handle_endtag(self, tag): print('handle_endtag:','</%s>' % tag) def handle_startendtag(self, tag, attrs): print('handle_startendtag:','<%s/>' % tag) def handle_data(self, data): print('data:',data) def handle_comment(self, data): print('<!--', data, '-->') def handle_entityref(self, name): print('&%s;' % name) def handle_charref(self, name): print('&#%s;' % name) myHtmlParser = MyHTMLParser() myHtmlParser.feed('''<html> <head></head> <body> <!-- test html parser --> <p>Some <a href=\"#\">html</a> HTML tutorial...<br>END</p> </body></html>''') myHtmlParser.feed(data.decode('UTF-8')) print('page title is: %s' %myHtmlParser.content) # 导入turtle包的所有内容: from turtle import * # 设置笔刷宽度: width(4) # 前进: forward(200) # 右转90度: right(90) # 笔刷颜色: pencolor('red') forward(100) right(90) pencolor('green') forward(200) right(90) pencolor('blue') forward(100) right(90) # 调用done()使得窗口等待被关闭,否则将立刻关闭窗口: done()
参考文档:https://www.liaoxuefeng.com/wiki/1016959663602400/1016959856222624