Python Notepad#1

Datatypes 大蛇的数据类型
1、dyanmically typed: Types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.
动态类型:数据类型在执行的时候才被确定,和静态类型相反。大蛇和vbs类似,它们都在第一次赋值的时候才确定变量的类型。
2、strongly typed: Types are always enforced. Java and Python are strongly typed. If you have an integer, you can’t treat it like a string without explicitly converting it.
强类型:数据类型总是被强调,大蛇和java都是强类型。例如,整型不能被当成字符串对待,除非明确转换成字符串。@Diky: str(a_int)
Once a variable has a datatype, it actually matters.
当变量有了数据类型,就需要在乎这件事(?)
@Diky:
1、在使用涉及SQL的类和方法的时候,考虑将全部输入都强制转换成字符串(包括整型,None除外),这样用的时候就不用考虑太多。
2、或者是什么就用什么,OO就要反映真实的世界(被踢飞)
3、还有麻烦的编码问题,如果不能够自动检测编码,就每种编码都try-except一下直到牺牲好了。

Documenting 函数的文档(doc)
不同于注释,特指一个函数的说明性文字。
@Diky:
1、类可以用吗?
2、以前一直用#,要用”””内容(多行)”””。
3、如果有文档,必须在冒号之后马上跟随。它可以作为函数的变量被调用。
You don’t technically need to give your function a doc string, but you always should.

print yourFunction.__doc__
@Diky:返回doc。

@Diky:关于OO,我想应该将任何东西都放到类里面……例如首页只有一句话:myProgram(myConfiguration(Environment_Int), other, …)

When you want to use functions defined in imported modules, you need to include the module name.
要用模块的函数要跟上模块名。@Diky:为了代码可以被到处复制,考虑什么时候用 from XXX import XXX。

导入模块的路径问题

>>> import sys—————–1
>>> sys.path——————-2
[”, ‘/usr/local/lib/python2.2’, ‘/usr/local/lib/python2.2/plat-linux2’,
‘/usr/local/lib/python2.2/lib-dynload’, ‘/usr/local/lib/python2.2/site-packages’,
‘/usr/local/lib/python2.2/site-packages/PIL’, ‘/usr/local/lib/python2.2/site-packages/piddle’]
>>> sys————————3
<module ‘sys’ (built-in)>
>>> sys.path.append(‘/my/new/path’)-4

@Diky:
1、对本地/远程调试、Linux Cron Job很重要,因为Cron Job调用自制模块时需要绝对路径,到现在还搞不太清楚。
2、可以手动增加系统路径,不过我更关心如何让一个相对路径的模块无论如何都能被调用。

大蛇对象
In Python, the definition is looser; some objects have neither attributes nor methods , and not all objects are subclassable. But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function.
有些对象冇变量冇方法,有些对象不能被继承。不过从意义上讲,对象是因为1、可以被赋值2、可以作为参数传递给函数。
Everything in Python is an object。大蛇的所有东西都是对象。
@Diky:被封装的世界啊。

代码识别缩进:不一定是4个空格,但一定要是同样的缩进。
@Diky:所以如果用notepad2去写代码就要将制表符弄成4空格模式。

print ‘some text’,
@Diky:
1、这个逗号的意思不是不换行,而是print可以连续输出若干个对象:print ‘text1’, ‘text2’,从这个层面去理解。
2、我觉得print应该不输出回车,就不会出现这种奇怪的语法和理解方法了。

Python does not support in-line assignment, so there’s no chance of accidentally assigning the value you thought you were comparing.
大蛇不支持嵌入式比较兼赋值(i==i++这种?),所以没有什么解析上的麻烦。

对象的固有属性__name__
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__.
如果是import的,那么模块的__name__的值就是模块名;如果直接运行它,那值就变成__main__。
@Diky:一个模块被直接运行的话执行代码A,被引用就不执行,就应该将A放到这个判断之中。
Knowing this, you can design a test suite for your module within the module itself by putting it in this if statement. …This makes it easier to develop and debug new modules before integrating them into a larger program.
@Diky:用来做测试挺好。

Native Datatypes
Dictionaries: 字典,好理解。
@Diky:我想一个Ac投稿的数据结构应该从7元素的list修改为7个元素的Dictionaries。面向现实吧,骚年。
字典是没有顺序的,不要考虑通过某种序列去访问它。
@Diky:为了更好地引用一个投稿对象,通过合适的方法使得acPost[‘ac_id’]变成acPost.ac_id。
1 Dictionaries aren’t just for strings. 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; you can mix and match as needed.
2 Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
大蛇的字典的value类型可以是混合的,但key类型有限制。@Diky:至少将key从[‘ac_id’]变成[ac_id],有没有这种定义方法?

del dict[‘key’]可以用来删除一个字典项。
dict.clear()方法清空掉字典,字典将变成{}。

List的负数序列号可以用来倒过来访问List,List[-1]表示最后一个元素。@Diky:非常方便。
子List
starting with the first slice index, up to but not including the second slice index.
List[1:3]:入手#1、#2元素
List[1:-1]:入手#1到最后一个元素(但不包含最后一个)
Reading the list from left to right, the first slice index specifies the first element you want, and the second slice index specifies the first element you don’t want.
1、先决定两个元素的位置;2、从左往右看;3、第一个元素表示其右边都是想要的,第二个元素表示其右边都是不想要的。
zero index可以去掉,也就是list[0:3]和list[:3]相同。
@Diky:
1、用实践来证明li[:]和li的不同:一个是引用,一个是赋值。

>>> li = [‘a’, ‘b’, ‘c’]
>>> li
[‘a’, ‘b’, ‘c’]
>>> li[:]
[‘a’, ‘b’, ‘c’]
>>> a=li
>>> a.append(‘d’)
>>> li
[‘a’, ‘b’, ‘c’, ‘d’]
>>> b=li[:]
>>> b.append(‘e’)
>>> li
[‘a’, ‘b’, ‘c’, ‘d’]
>>> b
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
2、程序2:参数传递指南
>>> def m(a):
…  a.append(‘a’)

>>> a=[‘a’]
>>> m(a)
>>> a
[‘a’, ‘a’]

List方法
append(value):加元素
insert(index, value):插入元素
extend(list):拼List
index(value):根据value输出index
value in list:测试list中是否有value
@Diky:比起自行try..except,大蛇已经提供了超赞的测试方法了。

额外:What is false
    * 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.

remove(value):删value,删左起第一个。
pop():和栈的pop一样,pop最后一个,并且输出它(可以print出来)。
List操作符
list = list + otherlist has the same result as list.extend(otherlist)
li += [‘two’] is equivalent to li.extend([‘two’])
li = [1, 2] * 3 is equivalent to li = [1, 2] + [1, 2] + [1, 2]

Tuples
不变的List。和List的区别是,用括号的。
可以入手子Tuple,规矩像list一样
不可以remove/insert/index,不过可以value in tuple的测试。
Tuple的好处:
1、更快,例如用来定义常量~\(≧▽≦)/~;
2、代码写保护;
3、可以用作字典key,但list不可以,因为字典key要求不变的。当然,用作tuple的key里面也不能有list这种可变的物体。
list(tuple)和tuple(list)可以用来在list和tuple间转化。

定义变量
    myParams = {“server”:”mpilgrim”, \
                “database”:”master”, \
                “uid”:”sa”, \
                “pwd”:”secret” \
                }
1、注意缩进;
2、backslash (“\”) serving as a line-continuation marker.
注:用了行连接的话下一行其实可以不缩进,但还是缩进吧。
不定义的话是不准引用的。有一天会感谢这个设定?
多重赋值

>>> v = (‘a’, ‘b’, ‘e’)
>>> (x, y, z) = v
>>> x
‘a’
>>> y
‘b’
>>> z
‘e’
连续赋值
>>> range(7)
[0, 1, 2, 3, 4, 5, 6]
>>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) 2
>>> MONDAY
0
>>> TUESDAY
1
>>> SUNDAY
6

格式化字符串
‘%s=%d’ % (str, id)
后面的部分是tuple,要注意到。

格式化字符串和操作符的比较

>>> uid = “sa”
>>> pwd = “secret”
>>> print pwd + ” is not a good password for ” + uid      1
secret is not a good password for sa
>>> print “%s is not a good password for %s” % (pwd, uid) 2
secret is not a good password for sa
>>> userCount = 6
>>> print “Users connected: %d” % (userCount, )           3 4
Users connected: 6
>>> print “Users connected: ” + userCount                 5
Traceback (innermost last):
  File “<interactive input>”, line 1, in ?
TypeError: cannot concatenate ‘str’ and ‘int’ objects
1      + is the string concatenation operator.
2     In this trivial case, string formatting accomplishes the same result as concatentation.
3     (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.当tuple只有一个元素的时候,要加一个逗号;平时的话加不加都可以。
4     String formatting works with integers by specifying %d instead of %s.比起自行转换为Str,用这个会更好!重要!不要写垃圾代码了!
5     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.
格式化字符串和c一样有很多丰富的用法,略过了。

摆弄字符串、字典和列表(有例子就好理解)

>>> params = {“server”:”mpilgrim”, “database”:”master”, “uid”:”sa”, “pwd”:”secret”}
>>> params.keys()   1
[‘server’, ‘uid’, ‘database’, ‘pwd’]
>>> params.values() 2
[‘mpilgrim’, ‘sa’, ‘master’, ‘secret’]
>>> params.items()  3
[(‘server’, ‘mpilgrim’), (‘uid’, ‘sa’), (‘database’, ‘master’), (‘pwd’, ‘secret’)]
>>> params.items()
[(‘server’, ‘mpilgrim’), (‘uid’, ‘sa’), (‘database’, ‘master’), (‘pwd’, ‘secret’)]
>>> [k for k, v in params.items()]
[‘server’, ‘uid’, ‘database’, ‘pwd’]
>>> [v for k, v in params.items()]
[‘mpilgrim’, ‘sa’, ‘master’, ‘secret’]
>>> [“%s=%s” % (k, v) for k, v in params.items()]
[‘server=mpilgrim’, ‘uid=sa’, ‘database=master’, ‘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’

关于join(list_of_str):列表一定要是字符串的列表,它不做类型转换。

拆str

>>> 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) #这个可选的参数1表示只拆1次
[‘server=mpilgrim’, ‘uid=sa;database=master;pwd=secret’]

 

发表评论

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

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