零碎python学习笔记(一) - 20121202

这篇博客记录了作者学习Python的初步体验,涉及三引号定义多行字符串、字符串转义、自然字符串、Unicode字符串、面向对象特性以及运算符的用法等基础知识。作者还探讨了Python中的`is`和`==`的区别,并分享了在StackOverflow上获取的关于恢复内置True和False的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天开始学习python……老早就想学学了,只是一直没空

Ok start...


用三引号定义多行字符串:

那么,如果要使用转义符打印三个连续引号('''或者"""),该如何用?

测试之。在多行字符串中,已经以三引号开头,那么可以直接使用转义符+三引号:

a = '''a\'''b'''
print a

输出:

a'''b

但是如果上例中没有b,那么解释器会将之理解成:

''' + a + \' + ''' + ' + '

即一个多行字符串a'和一个空字符串合并,结果是

a'

如果用单引号定义字符串,那么串中的双引号无特殊含义,不需使用转义符

反之亦然。

用三引号亦然。


定义自然字符串使用r+字符串:

a = r'\n\t\r'

定义Unicode字符串用u+字符串:

# coding=GBK

...

a = u'已以'

那么定义Unicode的自然字符串呢?

经测试,应使用ur+字符串.

ru+字符串会报错。

a = ur'已\n以'


给面向对象编程用户的注释
就每一个东西包括数、字符串甚至函数都是对象这一点来说,Python是极其完全地面向对象的。

那么这一点与java不同


教程中并未提及 '++'操作符

测试发现:

i++ 不工作:报错

++i不报错,但是似乎没有干任何事情,i的值并不改变。

所以……唉,没有++ -- 真不习惯,尽量吧。

**是幂的意思。

//同除法但将商取整。

>>和<<比特左右移位还在。善!

&&, || 和 !变成了 and, or 和 not,好吧也许这样更可读。


分行符:

python中可以使用分号;作为分行符……也可以不使用,如果没有把多个语句写一行的话。


变量命名的自由度还是很高的。测试可写:

True = False
if True:
    print 'xxxx'

解释通过,即定义新变量True,其值为假(False)

输入结果print 'xxxx'未运行

甚至可以写:

False = True
True = False
if True:
    print 'xxxx'

输出结果打印xxxx

嗯……希望我不会碰到这样的代码

那么如果像上例中一样全局定义被覆盖了怎么办?

我认为可以使用

True = 1==1
False = 1!=1

把它变回来。但是是否有其它更好的方法呢?

于是在stackoverflow上post了一个问题。希望会有人回答吧……链接在此

To Be Continued ... 先慢慢往下看吧


-更新:stackoverflow果然效率很高,已经有人回答了:

方法一,直接

del True

del False

就回归原始值了。

方法二,使用__buildin__.True/False

学习了。


Python里这些东西还是有点纠结的,窃以为学习语言时从一开始就该把这些纠结的地方弄清楚。

做了一些延伸查阅:

==和is:

==比较值是否相等

is比较是否指向同一个object

它们就像java中的==和object.equals()/compareTo()方法。(那么在python类中是否可以定义类似的方法呢?待调查)

经测,python中对于预定义好的类型(指比如java里的primitive types),似乎会作与字符串相同处理;即字面量其实是只读的,所有值相同的变量其实指向同一object,修改变量的值其实修改了它指向的地址(大概?未深入研究)。具体表现在:

a = 3
b = 3
print a==b

print a is b

结果:

True

True

说明它们似乎是指向同一object。

但是,如果是

a = 3

b = 3.0

print a==b

print a is b

结果:

True

False

类型不同,指向的object自然不同了。

(找到更准确说法:For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.


那么然后,根据Python的定义,所有非零非空的变量都会被 判断为true

这里判断为true并不意味着等于true。比如:

if 'aaa':

   do something

会执行do something代码。

但是

if 'aaa'==True: (或者 'aaa' is True)

  do something

就不会。


嗯嗯

另一个有可能会造成纠结的是运算符优先问题。根据教程:

运算符通常由左向右结合,即具有相同优先级的运算符按照从左向右的顺序计算。例如,2 + 3 + 4被计算成(2 + 3) + 4。一些如赋值运算符那样的运算符是由右向左结合的,即a = b = c被处理为a = (b = c)

写到这里我饿了……真饿啊。


嗯,没有switch语句……


嗯嗯,while循环后可以跟一个else……这个看起来很奇异,好好玩的样子。根据教程:else块事实上是多余的,因为你可以把其中的语句放在同一块(与while相同)中,跟在while语句之后,这样可以取得相同的效果。

更新:此处谬误。根据官网tutorial:loop’s else clause runs when no break occurs.

看来教材还是得看原版……

 

哈哈

那么do...while呢?没有看到。anyway,可以用

while True ... if ...:break

来实现。


for ... in ... loop:这个看起来和matlab里的for loop很相似,不错不错。range函数也可以接受step变量,如range(0, 10, 3)得到[0, 3, 6, 9]。但是没有C++里的灵活?不过需要那么灵活的话可以用while。C++和java中灵活的for loop用惯了还是很方便的。


差点忘了,重要而基本的问题:输入输出

s = raw_input('Enter something : ')

或者

guess = int(raw_input('Enter an integer : '))

输出直接print

文件输入输出么,之后再论。


函数内声明global变量——这个用起来还真不习惯。应该相当于一个声明,变量定义可以在声明之后或之前。


关键参数——这个真的很赞。不用写那么多重载函数了哇哈哈哈

偷一下懒,就用教程的例子:

def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c

func(37)
func(25, c=24)
func(c=50, a=100)

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)

This will print

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

 

Functions can also be called using keyword arguments of the form kwarg=value. For instance, the following function:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print "-- This parrot wouldn't", action,
    print "if you put", voltage, "volts through it."
    print "-- Lovely plumage, the", type
    print "-- It's", state, "!"

accepts one required argument (voltage) and three optional arguments (stateaction, and type). This function can be called in any of the following ways:

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

but all the following calls would be invalid:

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument

In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), and their order is not important. This also includes non-optional arguments (e.g. parrot(voltage=1000) is valid too). No argument may receive a value more than once.

 

def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments:
        print arg
    print "-" * 40
    keys = sorted(keywords.keys())
    for kw in keys:
        print kw, ":", keywords[kw]

It could be called like this:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")

 

注意这里参数表里的dict,key部分都没打引号,但似乎python自动将其转换成字符串。经查函数中这些key的确以字符串形式存储。

 

而加上引号反而会出错:

>>> cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           'shopkeeper'='Michael Palin',
           'client'="John Cleese",
           'sketch'="Cheese Shop Sketch")
SyntaxError: keyword can't be an expression

 

keyword中有空格也出错:

>>> cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shop keeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")
SyntaxError: invalid syntax

 

使用dict定义语法也出错:

>>> cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           'shop keeper':'Michael Palin',
           'client':"John Cleese",
           'sketch':"Cheese Shop Sketch")
SyntaxError: invalid syntax

 

嗯嗯。这其实只是keyword arguments变参输入的实现,而不应该理解为输入的就是一个dict。

 

文档字符串:

文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。 

大约类似于javadoc,但也不完全相同。


嗯嗯,有点累了,先到这里。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值