Python类的奇怪行为 [英] Odd behaviour of python's class
问题描述
这里是一个python类:
Here is a python class:
class TxdTest(object):
def __init__(self, name = '', atrributes = []):
self.name = name
self.attributes = atrributes
b $ b
然后我使用它像这样:
and then I use it like this:
def main():
for i in range(3):
test = TxdTest()
print test.name
print test.attributes
test.name = 'a'
test.attributes.append(1)
那么,结果是什么?结果是:
so, what's the result? The result is:
[]
[1]
[1,1]
为什么类中的self.attributes仍然获得值?
Why the 'self.attributes' in class still obtain the value ?
推荐答案
将可变对象(如列表)传递给python中的函数或方法时,调用函数或方法。这意味着无论何时调用该函数或方法(在这种情况下,您的 __ init __
方法),每次都使用完全相同的列表,继续前面的修改。
When passing a mutable object (like a list) to a function or method in python, a single object is used across all invocations of the function or method. This means that ever time that function or method (in this case, your __init__
method) is called, the exact same list is used every time, holding on to modifications made previously.
如果您希望有一个空列表作为默认列表,您应该执行以下操作:
If you want to have an empty list as a default, you should do the following:
class TxdTest(object):
def __init__(self, name = '', atrributes = None):
self.name = name
if attributes is None
self.attributes = []
else:
self.attributes = attributes
有关此工作原理的详细说明,请参阅:最少惊讶在Python中:可变默认参数,如bgporter所述。
For a detailed explanation of how this works see: "Least Astonishment" in Python: The Mutable Default Argument, as mentioned by bgporter.
这篇关于Python类的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!