设为首页 收藏本站
查看: 966|回复: 0

[经验分享] Python class 初始化参数为 list 等 可变类型时遇到的问题

[复制链接]

尚未签到

发表于 2015-10-26 12:28:04 | 显示全部楼层 |阅读模式




写了一个类,结果在初始化的时候,发现无论class怎么重新初始化,里面的list类型总是会带上上一个对象的内容,也就是无法清空


使用id()函数查看 class对应的attribute,结果发现id居然是一样的。。attribute变成了静态变量,以往使用强类型语言的经验直接傻了。。


查看了后面的文章发现:


    Python 默认初始化变量,只在def的时候做,也就是初始化以后,无论再如何操作,都不会执行默认变量,也就是import之后,就不会再初始化了


    如果要对可变变量进行初始化,则需要先使用占位类型(一般使用None)
   class test(arg=None):
if (test is None):
test = []
esle:
....





参考:http://effbot.org/zone/default-values.htm






Default Parameter Values in Python



Fredrik Lundh | July 17, 2008 | based on a comp.lang.python post


(It happened to me in one of the first Python programs I ever wrote, and it took several years before we spotted the (non-critical) bug, when someone looked a bit more carefully at the contents of a property file, and wondered what all those things were
doing there…)


Python’s handling of default parameter values is one of a few things that tends to trip up most new Python programmers (but usually only once).


What causes the confusion is the behaviour you get when you use a “mutable” object as a default value; that is, a value that can be modified in place, like a list or a dictionary.


An example:


>>> def function(data=[]):
...     data.append(1)
...     return data
...
>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]


As you can see, the list keeps getting longer and longer. If you look at the list identity, you’ll see that the function keeps returning the same object:


>>> id(function())
12516768
>>> id(function())
12516768
>>> id(function())
12516768


The reason is simple: the function keeps using the same object, in each call. The modifications we make are “sticky”.



Why does this happen?



Default parameter values are always evaluated when, and only when, the “def” statement they belong to is executed; see:




http://docs.python.org/ref/function.html



for the relevant section in the Language Reference.


Also note that “def” is an executable statement in Python, and that default arguments are evaluated in the “def” statement’s environment. If you execute “def” multiple times, it’ll create a new function object (with freshly calculated default values) each time.
We’ll see examples of this below.



What to do instead?



The workaround is, as others have mentioned, to use a placeholder value instead of modifying the default value.None is a common value:


def myfunc(value=None):
if value is None:
value = []
# modify value here


If you need to handle arbitrary objects (including None), you can use a sentinel object:


sentinel = object()
def myfunc(value=sentinel):
if value is sentinel:
value = expression
# use/modify value here


In older code, written before “object” was introduced, you sometimes see things like


sentinel = ['placeholder']


used to create a non-false object with a unique identity; [] creates a new list every time it is evaluated.



Valid uses for mutable defaults



Finally, it should be noted that more advanced Python code often uses this mechanism to its advantage; for example, if you create a bunch of UI buttons in a loop, you might try something like:


for i in range(10):
def callback():
print "clicked button", i
UI.Button("button %s" % i, callback)


only to find that all callbacks print the same value (most likely 9, in this case). The reason for this is that Python’s nested scopes bind to variables, not object values, so all callback instances will see the current (=last) value of the “i” variable.
To fix this, use explicit binding:


for i in range(10):
def callback(i=i):
print "clicked button", i
UI.Button("button %s" % i, callback)


The “i=i” part binds the parameter “i” (a local variable) to the current value of the outer variable “i”.


Two other uses are local caches/memoization; e.g.


def calculate(a, b, c, memo={}):
try:
value = memo[a, b, c] # return already calculated value
except KeyError:
value = heavy_calculation(a, b, c)
memo[a, b, c] = value # update the memo dictionary
return value


(this is especially nice for certain kinds of recursive algorithms)


and, for highly optimized code, local rebinding of global names:


import math
def this_one_must_be_fast(x, sin=math.sin, cos=math.cos):
...


How does this work, in detail?



When Python executes a “def” statement, it takes some ready-made pieces (including the compiled code for the function body and the current namespace), and creates a new function object. When it does this, it also evaluates the default values.


The various components are available as attributes on the function object; using the function we used above:


>>> function.func_name
'function'
>>> function.func_code
<code object function at 00BEC770, file &quot;<stdin>&quot;, line 1>
>>> function.func_defaults
([1, 1, 1],)
>>> function.func_globals
{'function': <function function at 0x00BF1C30>,
'__builtins__': <module '__builtin__' (built-in)>,
'__name__': '__main__', '__doc__': None}


Since you can access the defaults, you can also modify them:


>>> function.func_defaults[0][:] = []
>>> function()
[1]
>>> function.func_defaults
([1],)


However, this is not exactly something I’d recommend for regular use…


Another way to reset the defaults is to simply re-execute the same “def” statement. Python will then create a new binding to the code object, evaluate the defaults, and assign the function object to the same variable as before. But again, only do that if you
know exactly what you’re doing.


And yes, if you happen to have the pieces but not the function, you can use the function class in the new module to create your own function object.


版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-130957-1-1.html 上篇帖子: 牛人总结python中string模块各属性以及函数的用法,果断转了,好东西 下篇帖子: Python入门:字符串与字节互转
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表