Python 有两个内建的模块用于处理命令行参数:
一个是 getopt,getopt只能简单处理 命令行参数。
另一个是 optparse,是一个能够让程式设计人员轻松设计出简单明了、易于使用、符合标准的Unix命令列程式的Python模块。生成使用和帮助信息。

用法

  • import OptionParser 类
  • 创建一个 OptionParser 对象
  • 使用 add_option 来定义命令行参数
    阅读全文 »

time

通常有这几种方式来表示时间

  • 时间戳
  • 格式化的时间字符串
  • 元组(struct_time)共九个元素,(年,月,日,时,分,秒,周,一年中的第几天,夏令时)

特殊函数说明

time.time() 获取当前时间戳
time.localtime() 当前时间的struct_time形式
time.ctime() 当前时间的字符串形式

strftime(…)
strftime(format[, tuple]) -> string
将指定的struct_time(默认为当前时间),根据指定的格式化字符串输出

clock()
clock() -> floating point number
该函数有两个功能,
在第一次调用的时候,返回的是程序运行的实际时间;
以第二次之后的调用,返回的是自第一次调用后,到这次调用的时间间隔

阅读全文 »

魔法方法用前后双下划线的方式标示

构造函数(init

当一个对象被创建时,会立即调用构造方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

>>> class Rectangle:
... def __init__(self,x,y):
... self.x = x
... self.y = y
... def getperl(self):
... return (self.x + self.y)*2
... def getarea(self):
... return self.x * self.y
...

#结果
>>> rec = Rectangle(3,4)
>>> rec.getperl()
14
>>> rec.getarea()
12

构造函数的实质是在最初的调用new函数

1
2
3
4
5
6
7
8
9
10
>>> class Capstr(str):   
... def __new__(cls,string):
... string = string.upper()
... return str.__new__(cls,string)
...

#结果
>>> a = Capstr("i am vike")
>>> a
'I AM VIKE'
阅读全文 »

迭代器

迭代器:就是具有next方法的对象。在调用next方法时,迭代器会返回它的下一个值;当没有值可以返回时,会引发一个StopIteration异常。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> def gennum(n):
... i = 1
... while i <= n:
... yield i**2
... i +=1
...
>>> g1=gennum(5)
>>> g1.next()
1
>>> g1.next()
4
>>> g1.next()
9
>>> g1.next()
16
>>> g1.next()
25
>>> g1.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
阅读全文 »

类中常见的一些函数

callable(object) 确定对象是否可调用
hasattr(object,name) 确定对象是否有给定的特性
isinstance(object,class) 确定对象是否是类的实例
issubcleass(A,B) 确定A是否为B的子类
random.choice(sequence) 从非空序列中随机选择元素

阅读全文 »