我的python & django (2) 2007-7-8

来源:互联网 发布:自我意识觉醒 知乎 编辑:程序博客网 时间:2024/05/21 10:48

Django settings

http://wiki.woodpecker.org.cn/moin/FrontPage

http://www.pyzen.cn/ http://blog.donews.com/limodou/

http://diveintopython.org/index.html

http://www.djangoproject.com/documentation/settings/ http://diveintopython.org/getting_to_know_python/everything_is_an_object.html http://www.python.org/

Dive Into Python http://diveintopython.org/toc/index.html

 

library search path -- Python looks in several places when you try to import a module -- Specifically, it looks in all the directories defined in sys.path.

>>> import sys

>>> sys.path

['D://Python24//Lib//idlelib', 'C://WINDOWS//system32//python24.zip', 'D:// Python24', 'D://Python24//DLLs', 'D://Python24//lib', 'D://Python24//lib//plat

-win', 'D://Python24//lib//lib-tk', 'D://Python24//lib//site-packages']

>>> sys

<module 'sys' (built-in)>

>>> sys.path.append('/my/new/path') -- The effect lasts as long as Python is running.

def buildConnectionString(params):

    """Build a connection string from a dictionary of parameters.

    Returns string."""

    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__": myParams = {"server":"mpilgrim", / "database":"master", /

                "uid":"sa", /

                "pwd":"secret" /

                } print buildConnectionString(myParams)

result  -- pwd=secret;database=master;uid=sa;server=mpilgrim

 

join() is a method on string objects

 

Python is both dynamically typed (because it doesn't use explicit datatype declarations) and strongly typed (because once a variable has a datatype, it actually matters).

Triple quotes signify a multi-line string. Everything between the start and end quotes is part of a single string, including carriage returns and other quote characters. You can use them anywhere, but you'll see them most often used when defining a doc string.

Everything between the triple quotes is the function's doc string, which documents what the function does. A doc string, if it exists, must be the first thing defined in a function (that is, the first thing after the colon). You don't technically need to give your function a doc string, but you always should. I know you've heard this in every programming class you've ever taken , but Python gives you an added incentive: the doc string is available at runtime as an attribute of the function.

Modules are objects, and all modules have a built-in attribute __name__. A module's __name__ depends on how you're using the module. If you import the module, then __name__ is the module's filename, without a directory path or file extension. But you can also run the module directly as a standalone program, in which case __name__ will be a special default value, __main__.

Defining a Dictionary

d = {"server":"mpilgrim", "database":"master"}

use

d

d[["database"]

to see the values

 Modifying a Dictionary

 d["database"] = "pubs"

 You can not have duplicate keys in a dictionary.

 You can add new key-value pairs at any time. Dictionary Keys Are Case-Sensitive Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type Dictionary keys are more restricted, but they can be strings, integers, and a few other types. Deleting Items from a Dictionary

d["database"] = "pubs"

del d[42]

d.clear()

Defining a List

 li = ["a", "b", "mpilgrim", "z", "example"]

 li[0] value is 'a'

li[-1]   --- li[-n] == li[len(li) - n]  --  value is 'example'

>>> li

['a', 'b', 'mpilgrim', 'z', 'example']

>>> li[1:3] 

 ['b', 'mpilgrim']

>>> li[1:-1]

 ['b', 'mpilgrim', 'z']

>>> li[0:3] 

 ['a', 'b', 'mpilgrim']

>>> li

['a', 'b', 'mpilgrim', 'z', 'example']

>>> li[:3]

 ['a', 'b', 'mpilgrim']

>>> li[3:]

 ['z', 'example']

>>> li[:] 

 ['a', 'b', 'mpilgrim', 'z', 'example'] If both slice indices are left out, all elements of the list are included. But this is not the same as the original li list; it is a new list that happens to have all the same elements. li[:] is shorthand for making a complete copy of a list.

Adding Elements to a List

>>> li

 ['a', 'b', 'mpilgrim', 'z', 'example']

>>> li.append("new")

>>> li

 ['a', 'b', 'mpilgrim', 'z', 'example', 'new']

>>> li.insert(2, "new")

>>> li

['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']

>>> li.extend(["two", "elements"])

>>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

--Note that list elements do not need to be unique; there are now two separate elements with the value 'new', li[2] and li[6].

The Difference between extend and append

>>> li = ['a', 'b', 'c']

>>> li.extend(['d', 'e', 'f'])

 >>> li

 ['a', 'b', 'c', 'd', 'e', 'f']

>>> len(li)

6

>>> li[-1]

'f'

>>> li = ['a', 'b', 'c']

>>> li.append(['d', 'e', 'f'])

>>> li ['a', 'b', 'c', ['d', 'e', 'f']]

>>> len(li)

4

>>> li[-1] ['d', 'e', 'f']

Searching a List

>>> li

['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

>>> li.index("example")

5

 >>> li.index("new")

2

>>> li.index("c")

Traceback (innermost last): File "<interactive input>", line 1, in ? ValueError: list.index(x): x not in list

>>> "c" in li

False

 

index finds the first occurrence of a value in the list. In this case, 'new' occurs twice in the list, in li[2] and li[6], but index will return only the first index, 2.

To test whether a value is in the list, use in, which returns True if the value is found or False if it is not.

Python accepted almost anything in a boolean context:

    * 0 is false; all other numbers are true.

    * An empty string ("") is false, all other strings are true.

    * An empty list ([]) is false; all other lists are true.

    * An empty tuple (()) is false; all other tuples are true.

    * An empty dictionary ({}) is false; all other dictionaries are true.

These rules still apply in Python 2.2.1 and beyond, but now you can also use an actual boolean, which has a value of True or False. Note the capitalization ; these values, like everything else in Python, are case-sensitive.

 

Deleting List Elements

>>> li

['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

>>> li.remove("z")

>>> li

['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']

>>> li.remove("new")

>>> li

['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']

>>> li.remove("c")

Traceback (innermost last): File "<interactive input>", line 1, in ? ValueError: list.remove(x): x not in list

>>> li.pop()

'elements'

>>> li

['a', 'b', 'mpilgrim', 'example', 'new', 'two']

 

remove removes only the first occurrence of a value. In this case, 'new' appeared twice in the list, but li.remove("new") removed only the first occurrence.

 

pop is an interesting beast. It does two things: it removes the last element of the list, and it returns the value that it removed. Note that this is different from li[-1], which returns a value but does not change the list, and different from li.remove(value), which changes the list but does not return a value.

>>> li = ['a', 'b', 'mpilgrim']

>>> li = li + ['example', 'new']

>>> li

['a', 'b', 'mpilgrim', 'example', 'new']

>>> li += ['two']

>>> li ['a', 'b', 'mpilgrim', 'example', 'new', 'two']

>>> li = [1, 2] * 3

 >>> li [1, 2, 1, 2, 1, 2]

Lists can also be concatenated with the + operator. list = list + otherlist has the same result as list.extend(otherlist). But the + operator returns a new (concatenated) list as a value, whereas extend only alters an existing list. This means that extend is faster, especially for large lists.

Python supports the += operator. li += ['two'] is equivalent to li.extend([' two']). The += operator works for lists, strings, and integers, and it can be overloaded to work for user-defined classes as well.

The * operator works on lists as a repeater. li = [1, 2] * 3 is equivalent to li = [1, 2] + [1, 2] + [1, 2], which concatenates the three lists into one.

>>> t = ("a", "b", "mpilgrim", "z", "example")

>>> t

('a', 'b', 'mpilgrim', 'z', 'example')

>>> t[0]

'a'

>>> t[-1]

 'example'

>>> t[1:3]

 ('b', 'mpilgrim')

Note that when you slice a list, you get a new list; when you slice a tuple, you get a new tuple.

Tuples Have No Methods

>>> t ('a', 'b', 'mpilgrim', 'z', 'example')

>>> t.append("new")

Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'append' >>> t.remove("z") Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'remove'

>>> t.index("example")

Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'tuple' object has no attribute 'index'

>>> "z" in t

 True

Tuples have no append or extend method. Tuples have no remove or pop method. You can't find elements in a tuple. Tuples have no index method. You can, however, use in to see if an element exists in the tuple.

    * Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.

    * It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that shows this data is constant, and that special thought ( and a specific function) is required to override that.

    * Remember that I said that dictionary keys can be integers, strings, and “a few other types”? Tuples are one of those types. Tuples can be used as keys in a dictionary, but lists can't be used this way.Actually, it's more complicated than that. Dictionary keys must be immutable. Tuples themselves are immutable, but if you have a tuple of lists, that counts as mutable and isn't safe to use as a dictionary key. Only tuples of strings, numbers, or other dictionary-safe tuples can be used as dictionary keys.

    * Tuples are used in string formatting, as you'll see shortly.

Note Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple.

Also notice that the variable assignment is one command split over several lines, with a backslash (“/”) serving as a line-continuation marker.

Python has local and global variables like most other languages, but it has no explicit variable declarations. Variables spring into existence by being assigned a value, and they are automatically destroyed when they go out of scope.

Strictly speaking, expressions in parentheses, straight brackets, or curly braces (like defining a dictionary) can be split into multiple lines with or without the line continuation character (“/”). I like to include the backslash even when it's not required because I think it makes the code easier to read, but that's a matter of style.

Python will not allow you to reference a variable that has never been assigned a value; trying to do so will raise an exception.

Assigning multiple values at once

>>> v = ('a', 'b', 'e') >>> (x, y, z) = v >>> x 'a' >>> y 'b' >>> z 'e'

v is a tuple of three elements, and (x, y, z) is a tuple of three variables. Assigning one to the other assigns each of the values of v to each of the variables, in order.

Assigning Consecutive Values

>>> range(7 )                                                                    

[0, 1, 2, 3, 4, 5, 6] >>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7 ) 

>>> MONDAY                                                                       

0 >>> TUESDAY 1 >>> SUNDAY 6

The built-in range function returns a list of integers. In its simplest form, it takes an upper limit and returns a zero-based list counting up to but not including the upper limit. (If you like, you can pass other parameters to specify a base other than 0 and a step other than 1. You can print range.__doc__ for details.)

 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are the variables you're defining. (This example came from the calendar module, a fun little module that prints calendars, like the UNIX program cal. The calendar module defines integer constants for days of the week.)

Now each variable has its value: MONDAY is 0, TUESDAY is 1, and so forth.

>>> k = "uid" >>> v = "sa" >>> "%s=%s" % (k, v) 1 'uid=sa'

Note that (k, v) is a tuple.

String Formatting vs. Concatenating

>>> uid = "sa" >>> pwd = "secret" >>> print pwd + " is not a good password for " + uid

secret is not a good password for sa

>>> print "%s is not a good password for %s" % (pwd, uid)

secret is not a good password for sa

>>> userCount = 6

>>> print "Users connected: %d" % (userCount, )

Users connected: 6

>>> print "Users connected: " + userCount

Traceback (innermost last): File "<interactive input>", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects

        + is the string concatenation operator.

        In this trivial case, string formatting accomplishes the same result as concatentation.

       (userCount, ) is a tuple with one element. Yes, the syntax is a little strange, but there's a good reason for it: it's unambiguously a tuple. In fact , you can always include a comma after the last element when defining a list, tuple, or dictionary, but the comma is required when defining a tuple with one element. If the comma weren't required, Python wouldn't know whether ( userCount) was a tuple with one element or just the value of userCount.

       String formatting works with integers by specifying %d instead of %s. Trying to concatenate a string with a non-string raises an exception. Unlike string formatting, string concatenation works only when everything is already a string.

As with printf in C, string formatting in Python is like a Swiss Army knife. There are options galore, and modifier strings to specially format many different types of values.

Formatting Numbers

>>> print "Today's stock price: %f" % 50.4625   

50.462500

>>> print "Today's stock price: %.2f" % 50.4625 

50.46

>>> print "Change since yesterday: %+.2f" % 1.5

+1.50

        The %f string formatting option treats the value as a decimal, and prints it to six decimal places.

        The ".2" modifier of the %f option truncates the value to two decimal places.

        You can even combine modifiers. Adding the + modifier displays a plus or minus sign before the value. Note that the ".2" modifier is still in place, and is padding the value to exactly two decimal places.

>>> li = [1, 9, 8, 4]

>>> [elem*2 for elem in li]

[2, 18, 16, 8]

>>> li [1, 9, 8, 4]

>>> li = [elem*2 for elem in li]

>>> li [2, 18, 16, 8]

 

It is safe to assign the result of a list comprehension to the variable that you're mapping. Python constructs the new list in memory, and when the list comprehension is complete, it assigns the result to the variable.

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":" secret"}

>>> params.keys()

['server', 'uid', 'database', 'pwd']

>>> params.values()

['mpilgrim', 'sa', 'master', 'secret']

>>> params.items()

[('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', ' secret')]

return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

join works only on lists of strings; it does not do any type coercion. Joining a list that has one or more non-string elements will raise an exception.

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":" secret"}

>>> ["%s=%s" % (k, v) for k, v in params.items()]

['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']

>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])

'server=mpilgrim;uid=sa;database=master;pwd=secret'

>>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']

>>> s = ";".join(li) >>> s

'server=mpilgrim;uid=sa;database=master;pwd=secret'

 >>> s.split(";")

['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']

>>> s.split(";", 1) ['server=mpilgrim', 'uid=sa;database=master;pwd=secret']

 

原创粉丝点击