python函数的特性是什么_Python中你不知道的特性(下)

Python部落(www.freelycode.com)组织翻译, 禁止转载

错误的默认值会导致下面的结果>>> def foo(x=[]):...     x.append(1)...     print x... >>> foo()[1]>>> foo() [1, 1] # A should be [1]>>> foo()[1, 1, 1]

这时应该把默认值设置为None>>> def foo(x=None):...     if x is None:...         x = []...     x.append(1)...     print x>>> foo()[1]>>> foo()[1]

字典的__missing__内置方法

__missing__内置方法消除了KeyError异常, 重新定义了找不到Key时的返回.class MyDict(dict): # The function of creating a dictionary    def __missing__(self, key):        return key...>>> m = MyDict(a=1, b=2, c=3) >>> m{'a': 1, 'c': 3, 'b': 2}>>> m['a'] # The key exists and returns 11>>> m['z'] # Key does not exist and returns the name of the requested key'z'

以函数为变量

>>> def jim(phrase):...   return 'Jim says, "%s".' % phrase>>> def say_something(person, phrase):...   print person(phrase)>>> say_something(jim, 'hey guys')

更高阶的体现def f(x):    return x + 3def g(function, x):    return function(x) * function(x)print g(f, 7)

负的round>>> round(1234.5678, -2)1200.0>>> round(1234.5678, 2)1234.57

如果你想像C语言一样用{}代替缩进from __future__ import braces跳步切片a = [1,2,3,4,5]>>> a[::2]  # indicate step[1,3,5]或者反着跳>>> a[::-1] # Reverse list[5,4,3,2,1]在浏览器中打开页面import webbrowserwebbrowser.open_new_tab('http://facebook.com/') #Returns True and open tabzip合并列表a = [(1,2), (3,4), (5,6)]zip(*a)# [(1, 3, 5), (2, 4, 6)]在字典中合并两个列表>>> t1 = (1, 2, 3)>>> t2 = (4, 5, 6)>>> dict (zip(t1,t2)){1: 4, 2: 5, 3: 6}操作列表切片>>> a = range(10)>>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> a[:5] = [42] # All symbols up to 5 be replaced by "42">>> a[42, 5, 6, 7, 8, 9]>>> a[:1] = range(5) >>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> del a[::2] # Delete every second element>>> a[1, 3, 5, 7, 9]>>> a[::2] = a[::-2] # Alternative reserved>>> a[9, 3, 5, 7, 1]最后热爱未知, 阅读文档!英文原文: https://www.devbattles.com/en/sand/post-1799-Python_the_things_that_you_might_not_know译者: 诗书塞外

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值