Python Fundamental for Django

Strings
>>> s = 'django is cool'
>>> words = s.split()
>>> words
['django', 'is', 'cool']
>>> ' '.join(words)
'django is cool'
>>> s.count('o')
3
>>> s.find('go')
4
>>> s.replace('django', 'python')
'python is cool'

 

一些常用的string函数:

string methoddescription
count Number of occurrences of substring in string
find Search for substring [also see index, rfind, rindex]
join Merge substrings into single delimited string
replace Search and replace (sub)string
split Split delimited string into substrings [also see splitlines]
startswith Does string start with substring [also see endswith]
strip Remove leading and trailing whitespace [also see rstrip, lstrip]
title Title-case string [also see capitalize, swapcase]
upper UPPERCASE string [also see lower]
isupper Is string all UPPERCASE? [also see islower, and so forth]

 

格式化输出:

>>> '%s is number %d' % ('python', 1)
'python is number 1'
>>> hi = '''hello
baby'''
>>> hi
'hello\nbaby'
>>> print hi
hello

baby
Tuples

tuple里面的元素不能被修改,这与它本身的实现机制有关,在传递参数的时候如果不希望参数被修改也是一种不错的选择。

>>> a = ('one', 'two')
>>> a[0]
'one'
>>> c = ('only',)
>>> c[0]
'only'
>>> d = 'only',
>>> d[0]
'only'

这里需要注意的是声明一个tuple的时候关键是逗号,如果没有下面的例子就只是一个string,注意到这个非常重要,因为很多django的数据类型用的都是tuple:

>>> b = ('only')
>>> b[0]
'o'
 
Dictionaries

字典是一种有点像哈希表的列表,里面的元素有key和value两个属性。字典的元素可以修改,无序,且大小可以变化。如:

>>> book = {'title':'django', 'year':2008}
>>> 'title' in book
True
>>> book.get('pub', 'N/A')
'N/A'
>>> book['pub'] = 'Addision'
>>> book.get('pub', 'N/A')
'Addision'
>>> for key in book:
...     print key, ':', book[key]
...
year : 2008
title : django
pub : Addision

 

一些常用函数:

Dictionary MethodDescription 
keys Keys (also see iterkeys)  
values Values (also see itervalues)  
items Key-value pairs (also see iteritems)  
get Get value given key else default [also see setdefault, fromkeys]  
pop Remove key from dict and return value [also see clear, popitem]  
update Update dict with contents of (an)other dict  
 
Enumerate
>>> data = enumerate((123, 'abc', 'hello'))
>>> for i, value in data:
...     print i, value
...
0 123
1 abc
2 hello
Exception Handling

如尝试打开文件的异常处理:

try:
    f = open(filename, 'r')
except IOError, e:
    return False, str(e)

也可以把多种错误类型放到一个tuple里面,一次过检测:

try:
    process_some_data()
except (TypeError, ValueError,...), e:
    print "ERROR ", e

当然也可以对不同类型的异常用不同的处理方法,在最后一种情况通常加上一种Exception,因为这样可以包括所有的异常情况:

try:
    ...
except (TypeError, ValueError), e:
    ...
except ArithmeticError, e:
    ...
except Exception, e:
    ...
Files
>>> f = open('test.txt', 'w')
>>> f.write('foo\n')
>>> f.write('bar\n')
>>> f.close()
>>> f = open('test.txt', 'r')
>>> for line in f:
...     print line.rstrip()
...
foo
bar
>>> f.close()
Anonymous Functions

匿名函数使用关键字lambda,由一个表达式组成,代表函数的返回值。通常的使用方式:

lambda args: expression
sorted(list_of_people, key = lambda person: person.last_name)

# 等价于
def get_last_name(person):
    return person.last_name

sorted(list_of_people, key = get_last_name)
* args and ** kwargs

python里面的*不是C语言里面的指针,作为参数传递时,* 表示一个tuple(list), ** 表示dict

例子如下:

def check_web_server(host, port, path):
    ...

调用函数的时候一般用法:

check_web_server('127.0.0.1', 8080, '/admin/')

如果把参数作为一个tuple或者dict的形式,可以通过下标的形式传递参数,但是用 * 的方式可以非常方便的完成传参:

host_info = ('www.python.org', 80, '/')
check_web_server(host_info[0],host_info[1], host_info[2])

check_web_server(*host_info)

host_info = {'host': 'www.python.org', 'port': 80, 'path': '/'}
check_web_server(**host_info)
动态实例化

与其他的一些编程语言不同,python支持类的动态的实例化,如:

>>> class Book(object):
...     def __init__(self, name):
...         self.name = name
...
>>> john = Book('John')
>>> john.father = 'Jack'
>>> print john.father
Jack
posted @ 2014-09-08 20:31  Jolin123  阅读(498)  评论(0编辑  收藏  举报