├── Advancedfeatures.py ├── CheckPwd.py ├── DateTimeTest.py ├── Flask └── App.py ├── Function.py ├── HashLib.py ├── HelloWorld.py ├── HelloWorld.pyc ├── Http.py ├── ImagePillow.py ├── JSON_POST.py ├── JsonTest.py ├── MultiProcessiing.py ├── NamedTuple.py ├── OSTest.py ├── ProcessQueue.py ├── Python_Guide.py ├── README.md ├── StringIOTest.py ├── SubProcess.py ├── TestHello.py ├── ThreadLocalTest.py ├── ThreadLock.py ├── ThreadTest.py ├── class ├── Animal.py ├── EnumTest.py ├── Screen.py └── Student.py ├── dequeTest.py ├── generator.py ├── lambda.py ├── logging_text.py ├── qrcode.png ├── qrcode_for_gh_c68b033c3f15_344 (1).jpg ├── thumb.png └── wsgi ├── Server.py ├── WSGITest.py └── WSGITest.pyc /Advancedfeatures.py: -------------------------------------------------------------------------------- 1 | from collections import Iterable 2 | import os 3 | #Slice 4 | L=('Mark','Bob','Tracy') 5 | print L[0:3],L[:3],L[-1] 6 | 7 | L=range(1000) 8 | print L[:10] 9 | print L[-10:] 10 | print L[:10:2] 11 | print L[::10] 12 | 13 | print 'ABCDEFG'[:3] 14 | print 'ABCDEFG'[::2] 15 | d={'a':1,'b':2,'c':3} 16 | for key in d: 17 | print key 18 | for k,v in d.items(): 19 | print 'key:',k," value:",v 20 | 21 | for ch in 'ABC': 22 | print(ch) 23 | print isinstance(123,Iterable) 24 | #List Comprehensions 25 | print [x*x for x in range(1,11) if x%2 ==0] 26 | print [m+n for m in 'ABC' for n in 'DEF'] 27 | print [d for d in os.listdir('.')] 28 | d={'A':1,'B':2,'c':3} 29 | print [k.lower() + '+' +str(v) for k,v in d.items()] 30 | -------------------------------------------------------------------------------- /CheckPwd.py: -------------------------------------------------------------------------------- 1 | import sys,urllib,urllib2,getpass 2 | 3 | 4 | class TerminalPwd(urllib2.HTTPPasswordMgr): 5 | def find_user_password(self,realm,authuri): 6 | retval = urllib2.HTTPPasswordMgr.find_user_password(self,realm,authuri) 7 | 8 | if retval[0] == None and retval[1] == None: 9 | #didn't find it in stored values 10 | username = input("Login required,please input username:") 11 | password = input("please input password:") 12 | return(username,password) 13 | else: 14 | return retval 15 | 16 | 17 | url = "http://home.asiainfo.com/" 18 | req = urllib2.Request(url) 19 | 20 | 21 | opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(TerminalPwd())) 22 | 23 | 24 | fd = opener.open(req) 25 | 26 | print ("URL Retrieved:",fd.geturl()) 27 | info = fd.info() 28 | for key, value in info.items(): 29 | print "%s = %s" % (key,value) 30 | -------------------------------------------------------------------------------- /DateTimeTest.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | d = datetime.now() 3 | s = datatime(2015,4,5,12,23) 4 | print d 5 | print s.timestamp() 6 | -------------------------------------------------------------------------------- /Flask/App.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from flask import Flask 3 | from flask import request 4 | app = Flask(__name__) 5 | 6 | @app.route('/', methods=['GET', 'POST']) 7 | def home(): 8 | return '

Home

' 9 | 10 | @app.route('/signin', methods=['GET']) 11 | def signin_form(): 12 | return '''
13 |

14 |

15 |

16 |
''' 17 | 18 | @app.route('/signin', methods=['POST']) 19 | def signin(): 20 | # 需要从request对象读取表单内容: 21 | if request.form['username']=='admin' and request.form['password']=='password': 22 | return '

Hello, admin!

' 23 | return '

Bad username or password.

' 24 | 25 | if __name__ == '__main__': 26 | app.run() 27 | -------------------------------------------------------------------------------- /Function.py: -------------------------------------------------------------------------------- 1 | def my_abs(x): 2 | if x>0: 3 | return x 4 | else: 5 | return -x; 6 | print my_abs(-10) 7 | 8 | 9 | def power(x,n=2,a=1): 10 | s = 1 11 | while n >0: 12 | n = n-1 13 | s = s*x 14 | return s 15 | print power(2) 16 | 17 | print power(2,a=2) 18 | 19 | 20 | def add_end(L=None): 21 | if L is None: 22 | L = [] 23 | L.append('end') 24 | print L 25 | 26 | add_end() 27 | 28 | #a^2 + b^2 + c^3 29 | def calc(numbers): 30 | sum = 0 31 | for n in numbers: 32 | sum = sum + n*n; 33 | print sum 34 | 35 | calc([1,3,5,7]) 36 | 37 | #*->can be Change 38 | def calc(*numbers): 39 | sum = 0 40 | for n in numbers: 41 | sum = sum + n*n; 42 | print sum 43 | calc(1,3,5,7) 44 | 45 | # ** 46 | def calc(name,age,**kw): 47 | print('name:',name,'age:',age,'other:',kw) 48 | extra={'city':'Beijing','job':'Engineer'} 49 | calc('Mark',23,**extra) 50 | -------------------------------------------------------------------------------- /HashLib.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | md5 = hashlib.md5() 3 | md5.update('IamMarkA'.encode('utf-8')) 4 | print md5.hexdigest() 5 | -------------------------------------------------------------------------------- /HelloWorld.py: -------------------------------------------------------------------------------- 1 | #-*- coding:utf-8 -*- 2 | 3 | #中文 4 | __author__ = "Mark" 5 | import sys 6 | 7 | # _或者__表示private。 不应该被外部直接引用,但可以调用 8 | def __test(): 9 | args = sys.argv 10 | if len(args) == 1: 11 | print('Hello World') 12 | elif len(args) == 2: 13 | print('Hello,%s!' % args[1]) 14 | else: 15 | print('Too many args') 16 | if __name__ == '__main__': 17 | __test() 18 | -------------------------------------------------------------------------------- /HelloWorld.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiyouMc/PythonGuide/f57cc99fe3ac13fb2fca8f1bfb9ed326f9b2fd31/HelloWorld.pyc -------------------------------------------------------------------------------- /Http.py: -------------------------------------------------------------------------------- 1 | import sys,urllib,urllib2 2 | 3 | 4 | url = "http://mail.126.com" 5 | 6 | req = urllib2.Request(url) 7 | fd = urllib2.urlopen(req) 8 | 9 | 10 | print ("URL Retrieved:",fd.geturl()) 11 | info = fd.info() 12 | for key, value in info.items(): 13 | print "%s = %s" % (key,value) 14 | 15 | while True: 16 | data = fd.read(1024) 17 | if not len(data): 18 | break 19 | print data 20 | -------------------------------------------------------------------------------- /ImagePillow.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | im = Image.open('qrcode.png') 3 | print(im.format,im.size,im.mode) 4 | im.thumbnail((200,100)) 5 | im.save('thumb.png','JPEG') 6 | -------------------------------------------------------------------------------- /JSON_POST.py: -------------------------------------------------------------------------------- 1 | import urllib 2 | import urllib2 3 | import json 4 | 5 | url = "https://www.baidu.com" 6 | req = urllib2.Request(url) 7 | print req 8 | res_data = urllib2.urlopen(req) 9 | res = res_data.read() 10 | print res 11 | -------------------------------------------------------------------------------- /JsonTest.py: -------------------------------------------------------------------------------- 1 | import json 2 | d = dict(name='Mark',age=24,score=100) 3 | str = json.dumps(d) 4 | print str 5 | ob = json.loads(str) 6 | print ob 7 | 8 | class Student(object): 9 | def __init__(self,name,age,score): 10 | self.name = name 11 | self.age = age 12 | self.score= score 13 | 14 | def student2dict(std): 15 | return { 16 | 'name':std.name, 17 | 'age':std.age, 18 | 'score':std.score 19 | } 20 | s = Student('Mark',23,100) 21 | print(json.dumps(s,default=student2dict)) 22 | -------------------------------------------------------------------------------- /MultiProcessiing.py: -------------------------------------------------------------------------------- 1 | import os 2 | print('Process (%s) start...' % os.getpid()) 3 | pid = os.fork() 4 | if pid == 0: 5 | print('I am child process (%s) and my parent is %s' % (os.getpid(),os.getppid())) 6 | else: 7 | print('I (%s) just created a child process(%s)' % (os.getpid(),pid)) 8 | 9 | from multiprocessing import Pool 10 | import time,random 11 | 12 | def long_time_task(name): 13 | print('Run task %s (%s)...' % (name,os.getpid())) 14 | start = time.time() 15 | time.sleep(random.random() *3) 16 | end = time.time() 17 | print('Task %s runs %0.2f seconds.' % (name,(end-start))) 18 | if __name__=='__main__': 19 | print('Parent process %s.' % os.getpid()) 20 | p = Pool(3) 21 | for i in range(5): 22 | p.apply_async(long_time_task,args=(i,)) 23 | print('Waiting for all subprocesses done...') 24 | p.close() 25 | p.join() 26 | print('All subprocesses done.') 27 | -------------------------------------------------------------------------------- /NamedTuple.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | #namedtuple是一个函数,它用来创建一个自定义的tuple对象, 3 | #并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。 4 | from collections import namedtuple 5 | Point = namedtuple('Point',['x','y']) 6 | p = Point(1,2) 7 | print p.x,p.y 8 | -------------------------------------------------------------------------------- /OSTest.py: -------------------------------------------------------------------------------- 1 | import os 2 | print os.name,os.uname() 3 | print os.environ 4 | print os.environ.get('PATH') 5 | print os.path.abspath('.') 6 | print os.path.join(os.path.abspath('.'),'osTest') 7 | -------------------------------------------------------------------------------- /ProcessQueue.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | from multiprocessing import Process, Queue 3 | import os, time, random 4 | 5 | # 写数据进程执行的代码: 6 | def write(q): 7 | print('Process to write: %s' % os.getpid()) 8 | for value in ['A', 'B', 'C']: 9 | print('Put %s to queue...' % value) 10 | q.put(value) 11 | time.sleep(random.random()) 12 | 13 | # 读数据进程执行的代码: 14 | def read(q): 15 | print('Process to read: %s' % os.getpid()) 16 | while True: 17 | value = q.get(True) 18 | print('Get %s from queue.' % value) 19 | 20 | if __name__=='__main__': 21 | # 父进程创建Queue,并传给各个子进程: 22 | q = Queue() 23 | pw = Process(target=write, args=(q,)) 24 | pr = Process(target=read, args=(q,)) 25 | # 启动子进程pw,写入: 26 | pw.start() 27 | # 启动子进程pr,读取: 28 | pr.start() 29 | # 等待pw结束: 30 | pw.join() 31 | # pr进程里是死循环,无法等待其结束,只能强行终止: 32 | pr.terminate() 33 | -------------------------------------------------------------------------------- /Python_Guide.py: -------------------------------------------------------------------------------- 1 | import json 2 | data = {'b':123,'c':456,'a':'789'} 3 | 4 | d1 = json.dumps(data,sort_keys=True,indent=4); 5 | 6 | print d1 7 | print data 8 | 9 | 10 | print '''line1 11 | line2 12 | line3''' 13 | 14 | print 3>2 15 | 16 | print True and False 17 | 18 | print not True 19 | 20 | age = 17 21 | if age >18: 22 | print 'adult' 23 | else: 24 | print 'teenager' 25 | PI=1111 26 | print PI 27 | print 10.0/3 28 | #list 29 | classmates=['Mark','Bob','Tracy'] 30 | print classmates 31 | 32 | # list len 33 | print len(classmates) 34 | print classmates[0] 35 | 36 | # last 37 | print classmates[-1] 38 | classmates.append("Adam") 39 | print classmates 40 | classmates.insert(1,'aaaa') 41 | print classmates 42 | classmates.pop(); 43 | print classmates 44 | 45 | #tuple Not Change.diff list:not append insert 46 | noChange=('aa','bb') 47 | print noChange 48 | 49 | t = (1,) 50 | print t 51 | 52 | L = [ 53 | ['Apple', 'Google', 'Microsoft'], 54 | ['Java', 'Python', 'Ruby', 'PHP'], 55 | ['Adam', 'Bart', 'Lisa'] 56 | ] 57 | print L[0][0] 58 | print L[1][1] 59 | print L[2][2] 60 | 61 | #if...elif 62 | age = 3 63 | if age >= 18: 64 | print('adult') 65 | elif age >= 6: 66 | print('teenager') 67 | else: 68 | print('kid') 69 | s = '123' 70 | birth = int(s) 71 | if birth<200: 72 | print 'AAA' 73 | else: 74 | print 'BBB' 75 | 76 | #for in 77 | names=['Mark','Bob','Tracy'] 78 | for name in names: 79 | print name 80 | 81 | # 1+2....+1000 range 82 | sum=0 83 | for x in range(1000): 84 | sum = sum + x 85 | print sum 86 | 87 | n = 0 88 | while n < len(L): 89 | i = 0 90 | while i < len(L[n]): 91 | print L[n][i] 92 | i = 1+i 93 | n = 1+n 94 | #dict->Map 95 | d = {'Mark':95,'Bob':75,'Tracy':85} 96 | print d['Mark'] 97 | d.pop('Tracy') 98 | print d 99 | print d.get('Bob') 100 | print d.get('Tracy',-1) 101 | 102 | #set 103 | s = set([1,2,3]) 104 | print s 105 | s.add(4) 106 | print s 107 | s.remove(4) 108 | print s 109 | 110 | print abs(-100),max(1,2,3,47,1),min(1,2,3,40,4,0) 111 | print int('123') 112 | 113 | aa = abs 114 | print aa(-1),hex(255),hex(1000) 115 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PythonGuide 2 | This`s a guide of python. 3 | [中文说明](https://github.com/xiyouMc/PythonGuide/wiki) 4 | ```python 5 | import json 6 | data = {'b':123,'c':456,'a':'789'} 7 | 8 | d1 = json.dumps(data,sort_keys=True,indent=4); 9 | 10 | print d1 11 | print data 12 | 13 | 14 | print '''line1 15 | line2 16 | line3''' 17 | 18 | print 3>2 19 | 20 | print True and False 21 | 22 | print not True 23 | 24 | age = 17 25 | if age >18: 26 | print 'adult' 27 | else: 28 | print 'teenager' 29 | PI=1111 30 | print PI 31 | print 10.0/3 32 | #list 33 | classmates=['Mark','Bob','Tracy'] 34 | print classmates 35 | 36 | # list len 37 | print len(classmates) 38 | print classmates[0] 39 | 40 | # last 41 | print classmates[-1] 42 | classmates.append("Adam") 43 | print classmates 44 | classmates.insert(1,'aaaa') 45 | print classmates 46 | classmates.pop(); 47 | print classmates 48 | 49 | #tuple Not Change.diff list:not append insert 50 | noChange=('aa','bb') 51 | print noChange 52 | 53 | t = (1,) 54 | print t 55 | 56 | L = [ 57 | ['Apple', 'Google', 'Microsoft'], 58 | ['Java', 'Python', 'Ruby', 'PHP'], 59 | ['Adam', 'Bart', 'Lisa'] 60 | ] 61 | print L[0][0] 62 | print L[1][1] 63 | print L[2][2] 64 | 65 | #if...elif 66 | age = 3 67 | if age >= 18: 68 | print('adult') 69 | elif age >= 6: 70 | print('teenager') 71 | else: 72 | print('kid') 73 | s = '123' 74 | birth = int(s) 75 | if birth<200: 76 | print 'AAA' 77 | else: 78 | print 'BBB' 79 | 80 | #for in 81 | names=['Mark','Bob','Tracy'] 82 | for name in names: 83 | print name 84 | 85 | # 1+2....+1000 range 86 | sum=0 87 | for x in range(1000): 88 | sum = sum + x 89 | print sum 90 | 91 | n = 0 92 | while n < len(L): 93 | i = 0 94 | while i < len(L[n]): 95 | print L[n][i] 96 | i = 1+i 97 | n = 1+n 98 | #dict->Map 99 | d = {'Mark':95,'Bob':75,'Tracy':85} 100 | print d['Mark'] 101 | d.pop('Tracy') 102 | print d 103 | 104 | ``` 105 | 106 | http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919344c4ef8b1e04c48778bb45796e0335839000 107 | -------------------------------------------------------------------------------- /StringIOTest.py: -------------------------------------------------------------------------------- 1 | import StringIO 2 | f = StringIO.StringIO() 3 | f.write('hello\n') 4 | f.write(' ') 5 | f.write('world\n') 6 | print f.getvalue() 7 | f.close() 8 | 9 | t = StringIO.StringIO('hello\nworld\nTks\n') 10 | while True: 11 | s = t.readline() 12 | if s == '': 13 | break 14 | print(s.strip()) 15 | t.close() 16 | -------------------------------------------------------------------------------- /SubProcess.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | 4 | print('$ nslookup www.python.org') 5 | r = subprocess.call(['nslookup','www.python.org']) 6 | print('Exit code:',r) 7 | -------------------------------------------------------------------------------- /TestHello.py: -------------------------------------------------------------------------------- 1 | import HelloWorld 2 | HelloWorld.__test() 3 | -------------------------------------------------------------------------------- /ThreadLocalTest.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | import threading 3 | 4 | # 创建全局ThreadLocal对象: 5 | local_school = threading.local() 6 | 7 | def process_student(): 8 | # 获取当前线程关联的student: 9 | std = local_school.student 10 | print('Hello, %s (in %s)' % (std, threading.current_thread().name)) 11 | 12 | def process_thread(name): 13 | # 绑定ThreadLocal的student: 14 | local_school.student = name 15 | process_student() 16 | 17 | t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A') 18 | t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B') 19 | t1.start() 20 | t2.start() 21 | t1.join() 22 | t2.join() 23 | -------------------------------------------------------------------------------- /ThreadLock.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | import time,threading,multiprocessing 3 | # 假定这是你的银行存款: 4 | balance = 0 5 | lock = threading.Lock() 6 | def change_it(n): 7 | # 先存后取,结果应该为0: 8 | global balance 9 | balance = balance + n 10 | balance = balance - n 11 | 12 | def run_thread(n): 13 | for i in range(100000): 14 | lock.acquire() 15 | try: 16 | change_it(n) 17 | finally: 18 | lock.release() 19 | 20 | t1 = threading.Thread(target=run_thread, args=(5,)) 21 | t2 = threading.Thread(target=run_thread, args=(8,)) 22 | t1.start() 23 | t2.start() 24 | t1.join() 25 | t2.join() 26 | print(balance) 27 | 28 | print(multiprocessing.cpu_count()) 29 | -------------------------------------------------------------------------------- /ThreadTest.py: -------------------------------------------------------------------------------- 1 | import time,threading 2 | def loop(): 3 | print('thread %s is running...' % threading.current_thread().name) 4 | n = 0 5 | while n < 5: 6 | n = n + 1 7 | print('thread %s >>> %s' % (threading.current_thread().name, n)) 8 | time.sleep(1) 9 | print('thread %s ended.' % threading.current_thread().name) 10 | 11 | print('thread %s is running...' % threading.current_thread().name) 12 | t = threading.Thread(target=loop, name='LoopThread') 13 | t.start() 14 | t.join() 15 | print('thread %s ended.' % threading.current_thread().name) 16 | -------------------------------------------------------------------------------- /class/Animal.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | #继承 3 | class Animal(object): 4 | __slots__ = ('name','age') # 用tuple定义允许绑定的属性名称 5 | def run(self): 6 | print('Animal is running....') 7 | 8 | class Dog(Animal): 9 | def run(self): 10 | print('Dog is running...') 11 | pass 12 | class Cat(Animal): 13 | 14 | def run(self): 15 | print('Cat is running...') 16 | pass 17 | 18 | def run_twice(animal): 19 | animal.run(); 20 | dog = Dog(); 21 | dog.run() 22 | 23 | run_twice(Animal()) 24 | run_twice(Dog()) 25 | 26 | print type(dog) 27 | print dir(dog) 28 | 29 | #绑定方法 只对当前示例生效 30 | def set_age(self,age): 31 | self.age = age; 32 | s = Dog(); 33 | from types import MethodType 34 | s.set_age = MethodType(set_age,s); 35 | s.set_age(25) 36 | print s.age 37 | 38 | #给所有实例绑定方法 39 | Dog.set_age=set_age; 40 | dogTest = Dog() 41 | dogTest.set_age(22) 42 | print dogTest.age 43 | 44 | #__slots__限制绑定的属性名,子类不能被限制 45 | catSlots = Animal();#__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的 46 | catSlots.name = 'a' 47 | catSlots.age = 12 48 | #catSlots.score = 11; 49 | #print catSlots.score 50 | 51 | 52 | #property 可直接将方法变成属性来调用 53 | class Student(object): 54 | @property 55 | def score(self): 56 | return self._score 57 | 58 | @score.setter 59 | def score(self, value): 60 | if not isinstance(value, int): 61 | raise ValueError('score must be an integer!') 62 | if value < 0 or value > 100: 63 | raise ValueError('score must between 0 ~ 100!') 64 | self._score = value 65 | s = Student(); 66 | s.score = 60 67 | print s.score 68 | s.score = 9999 69 | print s.score 70 | -------------------------------------------------------------------------------- /class/EnumTest.py: -------------------------------------------------------------------------------- 1 | #-*- coding:utf-8 -*- 2 | 3 | from enum import Enum, unique 4 | 5 | @unique 6 | class Weekday(Enum): 7 | Sun = 0 # Sun的value被设定为0 8 | Mon = 1 9 | Tue = 2 10 | Wed = 3 11 | Thu = 4 12 | Fri = 5 13 | Sat = 6 14 | 15 | print Weekday.Sun 16 | -------------------------------------------------------------------------------- /class/Screen.py: -------------------------------------------------------------------------------- 1 | #-*-coding:utf-8 -*- 2 | 3 | class Screen(object): 4 | 5 | def __init__(self,name): 6 | self.name = name 7 | @property 8 | def width(self): 9 | return self._width 10 | 11 | @width.setter 12 | def width(self,value): 13 | self._width = value 14 | 15 | @property 16 | def height(self): 17 | return self._height 18 | 19 | @height.setter 20 | def height(self,value): 21 | self._height = value 22 | 23 | #只读 24 | @property 25 | def resolution(self): 26 | return self._width * self._height 27 | 28 | #__str__可格式化对象的内容。 类似java 的toString() 29 | def __str__(self): 30 | return 'Student object (name:%s)' % self.name 31 | __repr__ = __str__ 32 | s = Screen('AA') 33 | s._width = 1024 34 | s._height = 768 35 | print(s.resolution) 36 | print(s) 37 | s 38 | #实现for...in循环 39 | class Fib(object): 40 | def __init__(self): 41 | self.a,self.b = 0,1 42 | 43 | def __iter__(self):#实例本身就是迭代对象,故返回自己 44 | return self 45 | 46 | def nextr(self): 47 | self.a,self.b = self.b,self.a+self.b 48 | if self.a >1000: 49 | raise StopIteration(); 50 | return self.a; 51 | for n in Fib(): 52 | print n 53 | -------------------------------------------------------------------------------- /class/Student.py: -------------------------------------------------------------------------------- 1 | #-*- coding:utf-8 -*- 2 | #需要注意的是,在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。 3 | 4 | #有些时候,你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。 5 | 6 | #双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量: 7 | class Student(object): 8 | def __init__(self,name,score): 9 | self.__name = name; 10 | self.score = score; 11 | def __name(self): 12 | print self.__name 13 | 14 | def getName(self): 15 | return self.__name 16 | 17 | def print_self(self): 18 | print('%s:%s' %(self.__name,self.score)) 19 | 20 | bart = Student('Mark',100) 21 | print bart.getName(),bart.score; 22 | bart.print_self(); 23 | -------------------------------------------------------------------------------- /dequeTest.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | #使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。 3 | #deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈: 4 | from collections import deque 5 | q = deque(['a','b','c']) 6 | q.append('d') 7 | q.appendleft('y') 8 | print q 9 | 10 | from collections import Counter 11 | c = Counter() 12 | for ch in 'aaabbbccc': 13 | c[ch] = c[ch] + 1 14 | print c 15 | -------------------------------------------------------------------------------- /generator.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | from collections import Iterable 3 | from collections import Iterator 4 | g = (x* x for x in range(100)) 5 | print g 6 | for n in g: 7 | print n 8 | 9 | #Fibonacci 10 | def fib(max): 11 | n,a,b = 0,0,1 12 | while n max): 42 | break 43 | for x in triangles(20): 44 | print x 45 | 46 | 47 | print isinstance(iter('abc'), Iterator) 48 | 49 | print isinstance((x for x in range(10)), Iterator) 50 | -------------------------------------------------------------------------------- /lambda.py: -------------------------------------------------------------------------------- 1 | f = lambda x:x*x 2 | print f(5) 3 | -------------------------------------------------------------------------------- /logging_text.py: -------------------------------------------------------------------------------- 1 | import logging 2 | logging.basicConfig(level=logging.DEBUG) 3 | logging.info('aaaa') 4 | -------------------------------------------------------------------------------- /qrcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiyouMc/PythonGuide/f57cc99fe3ac13fb2fca8f1bfb9ed326f9b2fd31/qrcode.png -------------------------------------------------------------------------------- /qrcode_for_gh_c68b033c3f15_344 (1).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiyouMc/PythonGuide/f57cc99fe3ac13fb2fca8f1bfb9ed326f9b2fd31/qrcode_for_gh_c68b033c3f15_344 (1).jpg -------------------------------------------------------------------------------- /thumb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiyouMc/PythonGuide/f57cc99fe3ac13fb2fca8f1bfb9ed326f9b2fd31/thumb.png -------------------------------------------------------------------------------- /wsgi/Server.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | # server.py 3 | # 从wsgiref模块导入: 4 | from wsgiref.simple_server import make_server 5 | # 导入我们自己编写的application函数: 6 | from WSGITest import application 7 | 8 | # 创建一个服务器,IP地址为空,端口是8000,处理函数是application: 9 | httpd = make_server('', 8000, application) 10 | print('Serving HTTP on port 8000...') 11 | # 开始监听HTTP请求: 12 | httpd.serve_forever() 13 | -------------------------------------------------------------------------------- /wsgi/WSGITest.py: -------------------------------------------------------------------------------- 1 | def application(environ, start_response): 2 | start_response('200 OK', [('Content-Type', 'text/html')]) 3 | return [b'

Hello, web!

'] 4 | -------------------------------------------------------------------------------- /wsgi/WSGITest.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiyouMc/PythonGuide/f57cc99fe3ac13fb2fca8f1bfb9ed326f9b2fd31/wsgi/WSGITest.pyc --------------------------------------------------------------------------------