最近比较闲,想学习一门脚本语言,于是选择了python进行学习,之前对脚本语言不是很熟悉,所以不对python好坏做任何评价。希望通过学习python,能让自己对脚本语言有更深刻的认识吧。

Python的执行过程:当程序执行时,python内部会先将源代码编译成所谓的字节码的形式。字节码是源代码底层的、与平台无关的表现形式。编译字节码的过程中,会生成一个.pyc的文件,这个文件就是编译之后的字节码。Python真正在运行的就是这个字节码文件,如果生成字节码文件之后没有再修改过源代码的话,下次程序运行会跳过编译这个步骤,直接运行pyc文件,这是一种启动速度的优化。字节码文件被发送到python虚拟机(Python Virtual Machine, PVM)上来执行。PVM是python的运行引擎。

Python字节码不是机器的二进制代码,只是一种中间表示形式,所以python无法运行的和C/C++一样快。

Python语言有三种主要的实现方式:CPython、Jython和IronPython。

Python是动态类型的(自动跟踪你的类型而不是要求声明的代码),但也是强类型的(只能对一个对象进行有效的操作)

1 、十六进制和八进制表示 0XAF -> 175  , 010 ->8

2、math模块 import math ,使用的时候math.sqrt(100),当确定自己不会导入多个同名函数的情况下,可以使用from math import sqrt ,以后就可以随时使用sqrt函数了。

3、对于虚数的处理,使用cmath(complex math)模块,这样就可以对-1进行sqrt操作了。

4、input和raw_input的区别,input会假设用户输入的是合法的Python表达式,使用raw_input函数,它会把所有的输入当做原始数据(raw data),然后将其放在字符串中。除非input有特别的需要,否则应该尽可能使用raw_input函数

5、在字符串前面加r,取消转义

6、列表和元组的主要区别:列表可以修改而元组不能

7、列表的分片,列表[起始点,终止点之前一点,步长(默认为1)

8、字符串不能像列表一样被修改,一般转换为列表然后再进行处理

9、列表a、b,a=a+b的效率要低于a.extend(b),因为前者是在a+b后生成新的列表然后又赋值给a,而后者是在原a的基础上扩展出b的

10、pop方法是唯一一个能够修改列表又返回值的方法。lst.pop() 返回并删除

11、tuple函数将列表转化为元组 tuple([1,2,3])

12、模板字符串:string模块提供一种格式化值的方法:模板字符串。它的工作方式类似于很多UnixShell里的变量替换。 from string import Template 。 具体google。

13、string模块的join方法是split方法的逆方法。EG:seq = ['1','2','3','4','5'];sep = ',';s = sep.join(seq)

14、字符串的title方法,将字符串转换为标题,也就是所有单词的首字母大写,而其他字母小写。string = "that's all folks.";string.title()=="That'S All Folks."

15、strip方法返回去除两侧(不包括内部)空格的字符串。

16、使用dict的小Demo:

people = {

'Alice':{

'phone':1234,

'address':'beijing'

},

'Peter':{

'phone':4567,

'address':'shanghai'

},

'Micheal':{

'phone':9012,

'address':'hangzhou'

}

}

name = raw_input("please input the name : \n")

if(people.has_key(name)==False):

print "Not exist"

else:

profile = people[name]

#use dict to format the string

print "Phone is : %(phone)s \nAddress is : %(address)s" % profile

17、字典的拷贝,字典的普通copy方法是浅拷贝,只是简单的拷贝值,但是如果涉及到应用的拷贝的话,就要考虑使用deepcopy方法进行深拷贝。

18、模块的导入:

import somemodule

from somemodule import somefunction

from somemodule import somefunction, anthorfunction, yetanthorfunction

from somemodule import *

使用别名,避免冲突:import math as foobar

19、交换两个值 x,y = y,x

20、== 测试相等性,即值是否相等,而 is 用于测试同一性,即是否指向同一个对象

21、a if b else c ; 如果b为真,则返回a,否则返回c

22、遍历字典

d = {'x':1,'y':2,'z':3}

#Method1

for key in d:

print key ,'----->',d[key]

#Method2

for key in d.keys():

print key ,'----->',d[key]

#Method3

for (key , value) in d.items() :

print key , '----->' , value

23、zip函数可以用来进行并行迭代,可以将多个序列"压缩"在一起,然后返回一个元组的列表

names = ['Peter','Rich','Tom']

ages = [20,23,22]

d = dict(zip(names,ages))

for (name,age) in zip(names,ages):

print name ,'----', age

print d['Peter']

24、在循环中添加else语句,只有在没有调用break语句的时候执行。这样可以方便编写曾经需要flag标记的算法。

25、使用del时候,删除的只是名称,而不是列表本身值,事实上,在python中是没有办法删除值的,系统会自动进行垃圾回收。

26、求斐波那契数列

def fibs(num):

'a function document'

result = [0,1]

for i in range(num-2):

result.append(result[-2]+result[-1])

return result

27、抽象函数(参数可以缺省,可以通过*p传递任意数量的参数,传递的是元组;通过**p传递任意数量的参数,传递的是字典)

def a(*p):

print p

def b(**p):

print p

a(1,2,3)

b(a='1',b='2',c='3')

"""

result:

(1, 2, 3)

{'a': '1', 'c': '3', 'b': '2'}

"""

28、使用globals()函数获取全局变量值,该函数的近亲是vars,它可以返回全局变量的字典(locals返回局部变量的字典)

29、随机函数random.choice([1,2,3,4])

30、关于面向对象

#__metaclass__ = type

class Person:

#private variable

__name = ""

count = 0

def setname(self,name):

self.__name = name

def getname(self):

return self.__name

#private method using '__'

def __greet(self):

print "Say hello to %s !"%self.__name

def greet(self):

self.__greet()

def inc(self):

# ClassName.variableName means the variable belongs to the Class

# every instance shares the variable

Person.count+=1

#create instance

p = Person()

p.setname("Peter")

p.inc()

p2 = Person()

p2.setname("Marry")

p2.inc()

print "Name : " , p.getname()

#private method __Method is converted to public method _ClassName__Method

p._Person__greet()

print "Total count of person :  ", Person.count

p.count=12 # change the variable belong to the instance P

print p.count

print p2.count

31、python支持多重继承,如果一个方法从多个超类继承,那么必须要注意一下超类的顺序(在class语句中):先继承的类中方法会重写后继承的类中的方法,也就是后来将自动忽略同名的继承。

32、使用hasattr(tc,'talk') 判断对象tc时候包含talk属性; 使用callable(getattr(tc,'talk',None)) 判断对象tc的talk属性是否可以调用,但是在python3.0之后,callable方法已经不再使用了,可以使用hasattr(x,'__call__')代替callable(x);使用setattr可以动态设置对象的属性,setattr(tc,'talk',speek)

33、try:  except: else:    finally:    可以捕捉多个异常,多个异常用元组进行列出,并且可以捕捉对象,

def test():

while True:

try:

x = raw_input("Please input the x: ")

y = raw_input("Please input the y: ")

print int(x)//int(y)

except ZeroDivisionError as e:

print "The second number can not be zero"

print e

else:

print "Nothing exception has happened!"

finally:

print "Clean up . It will be executed all the time"

34、异常和函数:在函数内引发异常时,它就会被传播到函数调用的地方(对于方法也是一样)

35、构造方法:def __init__(self , arguments)

36、子类不会自动调用父类的构造方法

37、查看模块包含的内容可以使用dir函数,它会将对象(以及模块的所有函数、类、变量等)的所有特性列出.__all__变量定义了模块的共有接口(public interface)。更准确的说,它告诉解释器:从模块导入所有名字代表什么含义。eg: form copy import * 代码你只能访问__all__所定义的接口,而如果想访问其他接口的话,就必须显式地实现,from copy import PyStringMap

38、shelve模块的简单使用

'''

Created on 2011-12-11

A demo for shelve

@author: Peter

'''

import shelve

def store_person(db):

pid = raw_input("Enter the unique id for the person : ")

if pid in db :

print "The id exists , please change "

return

person = {}

person['name'] = raw_input("Enter the name of the person : ")

person['age'] = raw_input("Enter the age of the person : ")

person['phone'] = raw_input("Enter the phone number of the person : ")

db[pid] = person

def lookup_person(db):

pid = raw_input("Enter the id : ")

if pid not in db :

print "This is no that person"

return

field = raw_input("What would you like to know ? (name,age,phone) : ")

field = field.strip().lower()

print field.capitalize()+":"+db[pid][field]

def enter_command():

cmd = raw_input("Enter command : ")

cmd = cmd.strip().lower()

return cmd

def main():

database = shelve.open("database.bat")

try:

while True:

cmd = enter_command()

if cmd == 'store':

store_person(database)

elif cmd == 'lookup':

lookup_person(database)

elif cmd == 'exit':

return

finally:

database.close()

if __name__  == '__main__':main()

关于with和contextylib的用法:

平常Coding过程中,经常使用到的with场景是(打开文件进行文件处理,然后隐式地执行了文件句柄的关闭):

with file('test.py','r') as f :

print f.readline()

with的作用,类似try...finally...,提供一种上下文机制,要应用with语句的类,其内部必须提供两个内置函数__enter__以及__exit__。前者在主体代码执行前执行,后则在主体代码执行后执行。as后面的变量,是在__enter__函数中返回的。通过下面这个代码片段以及注释说明,可以清晰明白__enter__与__exit__的用法:

#!encoding:utf-8

class echo :

def output(self) :

print 'hello world'

def __enter__(self):

print 'enter'

return self #返回自身实例,当然也可以返回任何希望返回的东西

def __exit__(self, exception_type, exception_value, exception_traceback):

#若发生异常,会在这里捕捉到,可以进行异常处理

print 'exit'

#如果改__exit__可以处理改异常则通过返回True告知该异常不必传播,否则返回False

if exception_type == ValueError :

return True

else:

return False

with echo() as e:

e.output()

print 'do something inside'

print '-----------'

with echo() as e:

raise ValueError('value error')

print '-----------'

with echo() as e:

raise Exception('can not detect')

运行结果:

contextlib是为了加强with语句,提供上下文机制的模块,它是通过Generator实现的。通过定义类以及写__enter__和__exit__来进行上下文管理虽然不难,但是很繁琐。contextlib中的contextmanager作为装饰器来提供一种针对函数级别的上下文管理机制。常用框架如下:

from contextlib import contextmanager

@contextmanager

def make_context() :

print 'enter'

try :

yield {}

except RuntimeError, err :

print 'error' , err

finally :

print 'exit'

with make_context() as value :

print value

contextlib还有连个重要的东西,一个是nested,一个是closing,前者用于创建嵌套的上下文,后则用于帮你执行定义好的close函数。但是nested已经过时了,因为with已经可以通过多个上下文的直接嵌套了。下面是一个例子:

from contextlib import contextmanager

from contextlib import nested

from contextlib import closing

@contextmanager

def make_context(name) :

print 'enter', name

yield name

print 'exit', name

with nested(make_context('A'), make_context('B')) as (a, b) :

print a

print b

with make_context('A') as a, make_context('B') as b :

print a

print b

class Door(object) :

def open(self) :

print 'Door is opened'

def close(self) :

print 'Door is closed'

with closing(Door()) as door :

door.open()

运行结果:

python中start用法_Start Python 学习笔记(琐碎知识,持续更新。。。)相关推荐

  1. Vue -- 指令【学习笔记】(持续更新)

    Vue – 指令[学习笔记](持续更新) 记录了Vue第三天的学习笔记 v-show 注意,v-show 不支持 <template> 元素,也不支持 v-else. 带有 v-show ...

  2. python中没有arcpy怎么办_Arcpy学习笔记(一)—无中生有(上)

    一.前言 最近学习状态不是很好,理论学习进展缓慢.于是决定换换脑子,开始真正进行GIS与Python结合的相关学习,之后的文章会逐步记录学习路径与心得. 二.为什么要学习Arcpy?别问,问就是梦想 ...

  3. python中if语句使用_Python学习笔记之if语句的使用示例

    前言 条件语句在实际开发中我们已经使用过几次了,在这里我们需要再次隆重的来介绍一下它,下面话不多说了,来一起看看详细的介绍吧. if语句 顾名思义,该语句为判断语句,先来一个简单的示例 cars=[' ...

  4. Python中字符串格式化输出的学习笔记

    1 前言 此笔记讲述了如何对字符串进行格式化输出- 2 改变print()输出的颜色 这里我们可以通过字符串命令来改变**print()**输出的颜色: 例如下面的代码: def warning(*a ...

  5. python中sn的意思_python学习笔记

    学习资料:<简明 Python 教程.pdf>Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程. 特点:1.简单 2.易学 3.开源, ...

  6. python中forward的作用_Pytorch学习笔记07----nn.Module类与前向传播函数forward的理解

    1.nn.Module类理解 pytorch里面一切自定义操作基本上都是继承nn.Module类来实现的 方法预览: classModule(object):def __init__(self):de ...

  7. python中多维数组_python学习笔记-多维数组

    Python中初始化一个5 x 3每项为0的数组,最好方法是: multilist = [[0 for col in range(5)] for row in range(3)] 我们知道,为了初始化 ...

  8. Python中Hash值计算的学习笔记

    对于Hash算法的介绍,我们引用博文<Hash算法(含python实现) - yucen>中的介绍: 哈希(hash)也翻译作散列.Hash算法,是将一个不定长的输入,通过散列函数变换成一 ...

  9. 个人学习笔记汇总(持续更新)

    白墨的个人学习笔记 HTML JAVA Python MySQL 等待添加 说明 大家好,这里白墨,话不多说,先放笔记: HTML HTML笔记 JAVA JAVA笔记Myeclipse快捷键占位符的 ...

最新文章

  1. swift-初探webView与JS交互
  2. arduino并口屏_Arduino 驱动串口屏(入门级)
  3. OpenCV在浏览器中运行深度网络
  4. 高级T-SQL第1级的阶梯:使用交叉连接来引入高级T-SQL
  5. 升级到php7和安装拓展(mac centos)
  6. armgcc交叉编译的文件无法运行_认识GCC交叉编译器
  7. Mysql 执行流程
  8. 【转】C# 彻底搞懂async/await
  9. 比尔·盖茨推荐2020年度五本好书 你想读哪本?
  10. 使用CleanWipe卸载Symantec Endpoint Protection
  11. Kindle PaperWhite 3 5.8.10越狱成功!
  12. 鼠标滑轮成了页面缩放的解决方法
  13. macOS Monterey 12.4 (21F79) 正式版 ISO、IPSW、PKG 下载
  14. 京东淘宝手机销售量排行
  15. iOS上架详细通关教程(提交到AppStore)
  16. 元宇宙的东风吹向何处?企业如何乘势布局?
  17. Java多线程-Java多线程实现
  18. 程序员这样对待简历,你期望面试官怎么对待你?
  19. docker-部署lnmp
  20. 无忧SEO 网站推广技巧分享

热门文章

  1. SAP Commerce的extensioninfo.xml
  2. 开启SAP CDS view DCL前后的读取性能对比
  3. 使用SAP WebIDE进行SAP Cloud Platform Business Application开发
  4. SAP CRM IBASE对应的搜索实现,动态SQL语句的拼装
  5. 如何让Excel里显示的数字避免通过科学计数法来显示
  6. Hybris commerce的promotion rule里的固定折扣功能
  7. 2015-03-18 current note update logic in my task
  8. 如何在Android Studio里关掉instant run
  9. SAP gateway GWaaS single sign on
  10. dateFormat in DatePicker control Fiori - language 语言