让python代码更简洁 (2)


而是想用python写一个近似于 test?test_true_result:test_false_result的表达式,你可以写


test_true_result  if  test else test_false_result 或者

test and test_true_result or test_false_result


and 与 or

A and B 表达式取值为第一个 值为false的表达式,若全为真,取后一个

0 and 5  结果为 0

1 and 5  结果为 5

A or B   表达式取值为第一个 值为true的表达式,若全为假,取后一个

条件表达式也可写作,注意test_true_result 部分取值一定为True才会起到条件判断等效的作用,否则总会截断

6.函数部分


默认参数为可变类型时,要慎重!

因为def f1只解释加载一次,所以默认参数只赋值一次,call两次调用中,默认path指向的obj是同一个

def f(a ,list=[]):
list.append(a)
print list
print id(list)
if __name__ == '__main__':
f(1)
f(2)

输出结果:
[1]
20114168
[1, 2]
20114168

变长参数 与 变长关键字参数 来接受任意长度参数 或者 list  dict类型的参数


def do_something(a, b, c, *args):
print a, b, c, args

def do_something_else(a, b, c, *args, **kwargs):
print a, b, c, args, kwargs


关键字参数不能出现于非关键字参数前,不能重复赋值


def do_something(a, b, c, actually_print = True, *args):
if actually_print:
print a, b, c, args

do_something(1, 2, 3, 4, 5, actually_print = True)

wrong : TypeError: do_something() got multiple values for keyword argument 'actually_print'

do_something(1, 2, 3, actually_print = True, 4, 5, 6)

wrong:关键字参数只能出现在参数列表最后

do_something(1, 2, 3, True, 4, 5, 6)
right


装饰器是函数的包装,用来增前被修饰函数的功能,被修饰函数的执行返回传递给装饰器。


字典的get方法 可以用来实现switch条件语句

dict.get(key,defalutvalue);

#实现多函数入口
functions = {1: func1, 2: func2, 3: func3}
functions.get(keycode, default_func)()


7.类部分



对象作为方法参数

class Class:
def a_method(self):
print 'Hey a method'

instance = Class()
instance.a_method()
# prints 'Hey a method', somewhat unsuprisingly. You can also do:
Class.a_method(instance)

# prints 'Hey a method'


hasattr(Class,name_str)  判断属性或方法是否存在

getattr(Class,name_str,default_attr)  按名取类成员或返回默认值


类创建后可以修改

 1class Class:
2 def method(self):
3 print 'Hey a method'
4
5instance = Class()
6instance.method()
7# prints 'Hey a method'
8

9def new_method(self):
10 print 'New method wins!'
11
12Class.method = new_method
13instance.method()
14# prints 'New method wins!'


区别类方法(class method)、静态方法(static method)

前者以 @classmethod 修饰 知道自己所在类的信息,后者以@staticmethod 修饰仅提供一个全类共享方法

posted on 2011-09-29 11:06  oldcatzzz  阅读(334)  评论(0)    收藏  举报

导航