THE VERY BASIC

这里用来记录一些Python中最基础的东西

中文编码

Python中默认的编码格式是ASCII格式,所以打印汉字时要在文件开头声明编码。

# -*- coding: UTF-8 -*- 
或者
#coding=utf-8
import的搜索路径
  1. 当前目录
  2. PYTHONPATH下的每个目录
  3. 默认路径,UNIX下,一般为/usr/local/lib/python/
namespace

Python假设任何在函数内赋值的变量都是局部的,因此给函数内的全局变量赋值,必须使用global语句

reload()函数

当一个模块被导入到一个脚本,模块顶层部分的代码只会被执行一次。

因此,如果你想重新执行模块里顶层部分的代码,可以用 reload()函数。该函数会重新导入之前导入过的模块,这样就允许在不退出解释器的情况下重新加载已更改的Python模块。

包的结构

包中必须存在 __init__.py 文件, 该文件的内容可以为空。__init__.py 用于标识当前文件夹是一个包。

IO

raw_input([prompt]) 函数从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符)

str = raw_input("请输入:")
print "你输入的内容是: ", str
------------------------------
>>请输入:Hello Python!
>>你输入的内容是:  Hello Python!

input([prompt])raw_input([prompt]) 基本类似,但是 input 可以接收一个Python表达式作为输入,并将运算结果返回。

str = input("请输入:")
print "你输入的内容是: ", str
------------------------------
>>请输入:[x*5 for x in range(2,10,2)]
>>你输入的内容是:  [10, 20, 30, 40]
私有方法、属性
  • __private_attrs:两个下划线开头,声明该属性为私有
  • __private_method:两个下划线开头,声明该方法为私有方法

以使用 object._className__attrName访问私有属性,不能这样访问函数。

class Runoob:
    __site = "www.runoob.com"

runoob = Runoob()
print runoob._Runoob__site
-------------
>>www.runoob.com
下划线
  • __NAME__::定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。
  • _NAME:protected
  • __NAME:private
SQL
import MySQLdb

# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )

# 使用cursor()方法获取操作游标 
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d'" % (1000)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      # 打印结果
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"

#提交修改
db.commit()

#回滚
db.rollback()

# 关闭数据库连接
db.close()
多线程
thread模块

级别较低

import thread
 
# 为线程定义一个函数
def func(a, b):
   ...
 
# 创建两个线程
try:
   thread.start_new_thread( func, ("a", 1, ) )
   thread.start_new_thread( func, ("b", 2, ) )
except:
   print "Error: unable to start thread"
threading

直接从threading.Thread继承,然后重写__init__方法和run方法。

 
import threading
import time
 
exitFlag = 0
 
class myThread (threading.Thread):   
    def __init__(self):
        threading.Thread.__init__(self)
        
    def run(self):                  
        ...
 
# 创建新线程
thread1 = myThread()
thread2 = myThread()
 
# 开启线程
thread1.start()
thread2.start()
2018/8/13 posted in  Relearning Python