Python Notepad#2

函数调用
可选参数:def info(object, spacing=10, collapse=1)
多种调用方法
info(odbchelper)
info(odbchelper, 12)
info(odbchelper, collapse=0)
info(spacing=15, object=odbchelper)

Build-in Functions
type(object):显示对象的类型,可以用于任何对象,type自己、Module(import物)、None都行。
str(object):将任何对象转换成字符串,包括None;对list而言,不会自动connect各个item。
dir(object):列出对象的属性和方法。
callable(object):返回对象能否被调用的布尔值。
A string does have callable methods, but the string itself is not callable.
getattr:测试对象有没有某个属性;这个属性可以是任何对象。
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, ‘y’) is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn’t exist; without it, an exception is raised in that case.

[mapping-expression for element in source-list if filter-expression]
example.1理解性例子

>>> li = [“a”, “mpilgrim”, “foo”, “b”, “c”, “b”, “d”, “d”]
>>> [elem for elem in li if len(elem) > 1]       1
[‘mpilgrim’, ‘foo’]
>>> [elem for elem in li if elem != “b”]         2
[‘a’, ‘mpilgrim’, ‘foo’, ‘c’, ‘d’, ‘d’]
>>> [elem for elem in li if li.count(elem) == 1] 3
[‘a’, ‘mpilgrim’, ‘foo’, ‘c’]

example.2
methodList = [method for method in dir(object) if callable(getattr(object, method))]

关于and、or

>>> ‘a’ and ‘b’         1
‘b’
>>> ” and ‘b’          2

>>> ‘a’ and ‘b’ and ‘c’ 3
‘c’

1     When using and, values are evaluated in a boolean context from left to right. 0, ”, [], (), {}, and None are false in a boolean context; everything else is true. Well, almost everything. By default, instances of classes are true in a boolean context, but you can define special methods in your class to make an instance evaluate to false. You’ll learn all about classes and special methods in Chapter 5. If all values are true in a boolean context, and returns the last value. In this case, and evaluates ‘a’, which is true, then ‘b’, which is true, and returns ‘b’.
2     If any value is false in a boolean context, and returns the first false value. In this case, ” is the first false value.
3     All values are true, so and returns the last value, ‘c’.

>>> ‘a’ or ‘b’          1
‘a’
>>> ” or ‘b’           2
‘b’
>>> ” or [] or {}      3
{}
>>> def sidefx():
…     print “in sidefx()”
…     return 1
>>> ‘a’ or sidefx()     4
‘a’

1      When using or, values are evaluated in a boolean context from left to right, just like and. If any value is true, or returns that value immediately. In this case, ‘a’ is the first true value.
2     or evaluates ”, which is false, then ‘b’, which is true, and returns ‘b’.
3     If all values are false, or returns the last value. or evaluates ”, which is false, then [], which is false, then {}, which is false, and returns {}.
4     Note that or evaluates values only until it finds one that is true in a boolean context, and then it ignores the rest. This distinction is important if some values can have side effects. Here, the function sidefx is never called, because or evaluates ‘a’, which is true, and returns ‘a’ immediately.

and-or 玩笑
成功者:

>>> a = “first”
>>> b = “second”
>>> 1 and a or b
‘first’
>>> 0 and a or b
‘second’
失败者:a是False
>>> a = “”
>>> b = “second”
>>> 1 and a or b
‘second’
安全者:
>>> a = “”
>>> b = “second”
>>> (1 and [a] or [b])[0]

[]起到某种邪恶的作用了。

一根葱函数定义:lamda

>>> g = lambda x: x*2  1
>>> g(3)
6
>>> (lambda x: x*2)(3) 2
6

只是一个使用习惯,以免无聊的一句话函数被乱扔。

函数可以作为一个对象被存到一个参数里面。也就是说,通过合适的方法,可以让一个参数变成不同的想要的函数。

info@apihelper.py函数中的processFunc(str(getattr(object, method).__doc__)),要注意为何强制转换为str(因为__doc__可能为None,那就不能作为参数传递到processFunc,因为processFunc(s)又一个s.split()调用)

‘str’.ljust(int):补空格使得字符串达到int长度。
ljust pads the string with spaces to the given length. This is what the info function uses to make two columns of output and line up all the doc strings in the second column.

类名通常这样命名:ThisIsAClass

UserDict类:就像一个字典,可以继承它然后自制行为。

实例数据最好在__init__方法中全部声明好,不然在debug的时候会感到困扰。

__getitem__、__setitem__方法,使某个类用起来比较特殊。还是用例子说明:
FileInfo是继承自一个UserDict的类。

>>> f = fileinfo.FileInfo(“/music/_singles/kairo.mp3”)
>>> f
{‘name’:’/music/_singles/kairo.mp3′}
>>> f.__getitem__(“name”) 1
‘/music/_singles/kairo.mp3’
>>> f[“name”]             2
‘/music/_singles/kairo.mp3’
>>> f
{‘name’:’/music/_singles/kairo.mp3′}
>>> f.__setitem__(“genre”, 31) 1
>>> f
{‘name’:’/music/_singles/kairo.mp3′, ‘genre’:31}
>>> f[“genre”] = 32            2
>>> f
{‘name’:’/music/_singles/kairo.mp3′, ‘genre’:32}

__repr__:对象的表达。举例说明。

>>> class magic:
…     def __repr__(self):
…         return ”’you won’t know me.”’

>>> m=magic()
>>> m
you won’t know me.
>>> print m
you won’t know me.

__cmp__:用来决定a == b形式的比较行为。
__len__:len(object)行为。
__delitem__:del object行为;可以是del object[‘key’]=>object.__delitem__(self, key),这个方括号到底怎样界定的?

私有方法/属性:在方法/属性前面加上两个下划线,如__parse
私有方法也可以强制访问,但无论如何都别这样做。

因为Python有强大的List/Dict结构,所以可以避免很多无聊的loop。

os.path模块:用来处理文件路径,文件名,扩展名这些。
os.listdir(路径):相当于dos的dir;还有os.path.isfile和os.path.isdir可以用。
os.path.normcase:不同的系统对大小写的敏感度不同,这个方法可以根据系统的不同来决定如何处理文件名的大小写问题。

glob.glob方法:强大的文件搜索工具。

>>> os.listdir(“c:\\music\\_singles\\”)
[‘a_time_long_forgotten_con.mp3’, ‘hellraiser.mp3’,
‘kairo.mp3’, ‘long_way_home1.mp3’, ‘sidewinder.mp3’,
‘spinning.mp3’]
>>> import glob
>>> glob.glob(‘c:\\music\\_singles\\*.mp3’)
[‘c:\\music\\_singles\\a_time_long_forgotten_con.mp3’,
‘c:\\music\\_singles\\hellraiser.mp3’,
‘c:\\music\\_singles\\kairo.mp3’,
‘c:\\music\\_singles\\long_way_home1.mp3’,
‘c:\\music\\_singles\\sidewinder.mp3’,
‘c:\\music\\_singles\\spinning.mp3’]
>>> glob.glob(‘c:\\music\\_singles\\s*.mp3’)
[‘c:\\music\\_singles\\sidewinder.mp3’,
‘c:\\music\\_singles\\spinning.mp3’]
>>> glob.glob(‘c:\\music\\*\\*.mp3’)

RE指南
^    字符串开头
$    字符串尾。
\b    单词边界。(在大蛇中,\需要被转义,故表达成\\b)
\d    数字
\D    非数字
{n}、{n, m}重复n次,或重复n-m次
()    将小括号内的东西标记成一组,以便等下可以访问。
要反对python转义,用raw表达式:r’someregularexp’
+    +之前的内容重复1次或以上
*    *之前的内容重复0次或以上
c?    如果有,就必须是c;也就是说,没有任何东西也可以,但有就必须是c

稀疏(?)正则表达式:可以添加注释。

>>> pattern = “””
    ^                   # beginning of string
    M{0,4}              # thousands – 0 to 4 M’s
    (CM|CD|D?C{0,3})    # hundreds – 900 (CM), 400 (CD), 0-300 (0 to 3 C’s),
                        #            or 500-800 (D, followed by 0 to 3 C’s)
    (XC|XL|L?X{0,3})    # tens – 90 (XC), 40 (XL), 0-30 (0 to 3 X’s),
                        #        or 50-80 (L, followed by 0 to 3 X’s)
    (IX|IV|V?I{0,3})    # ones – 9 (IX), 4 (IV), 0-3 (0 to 3 I’s),
                        #        or 5-8 (V, followed by 0 to 3 I’s)
    $                   # end of string
    “””
>>> re.search(pattern, ‘M’, re.VERBOSE) #在使用的时候加上一个re.VERBOSE。
<_sre.SRE_Match object at 0x008EEB48>
>>> re.search(pattern, ‘MCMLXXXIX’, re.VERBOSE)
<_sre.SRE_Match object at 0x008EEB48>
>>> re.search(pattern, ‘MMMMDCCCLXXXVIII’, re.VERBOSE)
<_sre.SRE_Match object at 0x008EEB48>
>>> re.search(pattern, ‘M)

a = re.compile(pattern)
a.search(str).groups():返回一个tuple,包含找到的pattern中找到的组。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据