Python基础1:一些小知识汇总

一、#!usr/bin/env python

  脚本语言的第一行,指定执行脚本的解释器。

  #!/usr/bin/python 是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器;

  #!/usr/bin/env python 这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里。当系统看到这一行的时候,首先会到env设置里查找python的安装路径,再调用对应路径下的解释器程序完成操作。
    
  其语法规则是:

  1、必须是文件的第一行

  2、必须以#!开头

  3、/path/to/script/interpreter是脚本解释器的全路径名。

 例如:
#!/bin/sh shell脚本
#!/usr/bin/perl perl脚本
#!/usr/bin/python python脚本
#!/usr/bin/python3 python3脚本
#!/usr/bin/python2 python2脚本

另外,在指定解释器后,可以用#!coding = usf-8 来指定编码格式,这样在py文件中就可以写入中文注释或字符串。

二、__file__, __name__, __doc__属性

  1、__file__

  用来获得模块所在路径,得到的可能是相对路径或绝对路径。

  为了得到绝对路径,可以通过os.path.realpath(__file__)

  但是,在Python控制台下,直接使用print __file__是会导致  name ‘__file__’ is not defined错误的,因为这时没有在任何一个脚本下执行,自然没有 __file__的定义了。不过,在wing下的python shell中print __file__ ,会得到_sandbox.py的路径。如下图所示:

  

    

  sys.argv[0]是获取文件路径的另一种方式。

1 import os, sys
2 dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
3 print "running from", dirname
4 print "file is", filename
View Code

  不过,__file__与sys.argv[0]的区别在于:当一个文件访问另一个文件时,__file__显示的路径不同,sys.argv[0]显示的路径相同。表述的不是很清楚,见例子:

 1 #f:PythonWingPygameBunny and Badgers	est.py
 2 import sys, os
 3 print "test: sys.argv[0] is", repr(sys.argv[0])
 4 print "test: __file__ is", repr(__file__)
 5 print "test: cwd is", repr(os.getcwd())
 6 import pathutils
 7 pathutils.show_path()
 8 
 9 #D:Program FilesPython27pathutils.py
10 import os, sys
11 def show_path():
12     print "show_path: sys.argv[0] is", repr(sys.argv[0])
13     print "show_path: __file__ is", repr(__file__)
14     print "show_path: cwd is", repr(os.getcwd())
15 
16 #the output
17 test: sys.argv[0] is 'f:\Python\Wing\Pygame\Bunny and Badgers\test.py'
18 test: __file__ is 'f:\Python\Wing\Pygame\Bunny and Badgers\test.py'
19 test: cwd is 'f:\Python\Wing\Pygame\Bunny and Badgers'
20 show_path: sys.argv[0] is 'f:\Python\Wing\Pygame\Bunny and Badgers\test.py'
21 show_path: __file__ is 'D:\Program Files\Python27\pathutils.py'
22 show_path: cwd is 'f:\Python\Wing\Pygame\Bunny and Badgers'
View Code

  2、__name__

  用于判断当前模块是不是程序入口,如果当前程序正在使用,__name__的值为__main__。在编写程序时,通常需要给每个模块添加条件语句,用于单独测试该模块的功能。

  3、__doc__

  每个对象都有一个__doc__属性。

 1 class Person:
 2     '''print __doc__ will be displaied ....
 3        hahah
 4        heheh
 5     '''
 6     def __init__(self, name, age):
 7         self.name = name
 8         self.age = age
 9 bob = Person('bob', 18)    
10 print Person.__doc__
11 print bob.__doc__
12 
13 
14 '''
15 print __doc__ will be displaied ....
16        hahah
17        heheh
18     
19 print __doc__ will be displaied ....
20        hahah
21        heheh
22 '''
View Code

三、隐含参数*args,**kwargs

  直接用代码体现吧  

 1 def foo(*args,**kwargs):
 2   print 'args=',args
 3   print 'kwargs=',kwargs
 4   print '**********************'
 5 #if __name__=='__main__':
 6 foo(1,2,3)
 7 foo(a=1,b=2,c=3)
 8 foo(1,2,3,a=1,b=2,c=3)
 9 foo(1,'b','c',a=1,b='b',c='c')
10 
11 def foo2(**kwargs):
12   for item in kwargs.items():
13     print item,
14 my_dict = {'name': 'yy', 'age': 18}
15 foo2(**my_dict)  # '**' is must added
View Code

四、yield

  感觉yield是python特有的一个特性吧,用在生成器函数中。在python documention中有这样的描述,The yield expression is only used when defining a generator function, and can only be used in the body of a function definition. Using a yield expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

  而且,官方给出的例子很好的说明了yield的用法。

 1 def echo(value=None):
 2     print "Excution starts when 'next()' is called for the first time"
 3     try:
 4         while True:
 5             try:
 6                 value = (yield value)
 7             except Exception, e:
 8                 value = e
 9     finally:
10         print "Don't forget to clean up when 'close() is called.'"
11 
12 generator = echo(1)
13 print type(generator)
14 print generator.next()
15 print generator.next()
16 print generator.send(2)
17 print generator.throw(TypeError, "spam")
18 print generator.send("Does this work?")
19 generator.close()
View Code
 1 def myReadlines():
 2   seek = 0
 3   while True:
 4     with open('C:UsersAdministratorDesktopinterface.txt', 'r' ) as f:
 5       f.seek(seek)
 6       data = f.readline()
 7       if data:
 8         yield data
 9         seek = f.tell()
10       else:
11         return
12 
13 for item in myReadlines():
14   print item
View Code

五、lambda表达式

  lambda表达式相当于一个没有函数名的函数。当函数功能较简单,而不想声明一个函数时,可以用lambda表达式代替。上代码吧。

1 #example1
2 value = lambda x, y:x > y
3 print value(4, 6)
4 
5 #example2
6 map( lambda x: x*x, [y for y in range(10)] )
View Code

六、反射

  简单的说,就是以字符创的形式导入模块。__import__, getattr().

  第一次写博客,感觉挺好,以后就以这样的形式督促自己学习。反射机制下次再总结了,回去跑步。

  2016-03-26  21:07:00



原文地址:https://www.cnblogs.com/letgo/p/5324049.html