博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
The mutable default argument in Python
阅读量:5214 次
发布时间:2019-06-14

本文共 919 字,大约阅读时间需要 3 分钟。

>>> def a():...     print "a executed"...     return []... >>>            >>> def b(x=a()):...     x.append(5)...     print x... a executed>>> b()[5]>>> b()[5, 5]

Actually, this is not a design flaw, and it is not because of internals, or performance. It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code.

As soon as you get to think into this way, then it completely makes sense: a function is an object being evaluated on its definition; default parameters are kind of "member data" and therefore their state may change from one call to the other - exactly as in any other object.

In any case, Effbot has a very nice explanation of the reasons for this behavior in . I found it very clear, and I really suggest reading it for a better knowledge of how function objects work.

Related Link:

转载于:https://www.cnblogs.com/codingmylife/archive/2013/01/07/2849679.html

你可能感兴趣的文章
2018-2019-2 网络对抗技术 20165202 Exp3 免杀原理与实践
查看>>
NPM慢怎么办 - nrm切换资源镜像
查看>>
CoreData 从入门到精通(四)并发操作
查看>>
Swift - UIView的常用属性和常用方法总结
查看>>
Swift - 异步加载各网站的favicon图标,并在单元格中显示
查看>>
Java编程思想总结笔记Chapter 5
查看>>
[LeetCode]662. Maximum Width of Binary Tree判断树的宽度
查看>>
WinForm聊天室
查看>>
Python 从零学起(纯基础) 笔记(一)
查看>>
【Python学习笔记】1.基础知识
查看>>
梦断代码阅读笔记02
查看>>
Java 线程安全问题
查看>>
selenium学习中遇到的问题
查看>>
大数据学习之一——了解简单概念
查看>>
P1-13:集成日志组件 logback 2彩色日志
查看>>
Linux升级内核教程(CentOS7)
查看>>
Lintcode: Partition Array
查看>>
分享适合个人站长的5类型网站
查看>>
类别的三个作用
查看>>
【SICP练习】85 练习2.57
查看>>