Python constructor does weird things with optional parameters

Possible Duplicate: least astonishment in python: the mutable default argument I want to understand of the behavior and implications of the python __init__ constructor. It seems like when there is an optional parameter and you try and set an existing object to a new object the optional value of the existing object is preserved and copied. Look at an example: In the code below I am trying

Python构造函数使用可选参数来做奇怪的事情

可能重复: 最不惊讶的是python:可变的默认参数 我想了解python __init__构造函数的行为和含义。 看起来像有一个可选参数,并且您尝试将现有对象设置为新对象时,现有对象的可选值将被保留并复制。 看一个例子: 在下面的代码中,我试图制作一个带有节点和可能有很多孩子的树结构。 在第一类NodeBad ,构造函数有两个参数,值和任何可能的子NodeBad 。 第二类NodeGood只将该节点的值作为参数。 两者都有一个addchil

Python class constructor with default arguments

Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument Can anyone explain the following strange behaviour? I have the following class: class Zoo: def __init__(self,alist=[]): self.animals = alist def __len__(self): return len(self.animals) def add(self,a): self.animals.append(a) and when I do the following, In [38]: z=Zoo()

具有默认参数的Python类构造函数

可能重复: Python中的“最小惊讶”:可变的默认参数 任何人都可以解释以下奇怪的行为? 我有以下课程: class Zoo: def __init__(self,alist=[]): self.animals = alist def __len__(self): return len(self.animals) def add(self,a): self.animals.append(a) 当我做以下事情时, In [38]: z=Zoo() In [39]: z.add(2) In [40]: z.add(23) In [41]: len(z) Out[41]: 2 In [42]: z

Python class function default variables are class objects?

Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument I was writing some code this afternoon, and stumbled across a bug in my code. I noticed that the default values for one of my newly created objects was carrying over from another object! For example: class One(object): def __init__(self, my_list=[]): self.my_list = my_list one1 = One() print(one1.

Python类的函数默认变量是类对象吗?

可能重复: Python中的“最小惊讶”:可变的默认参数 我今天下午在写代码,偶然发现了代码中的一个错误。 我注意到,我的一个新创建的对象的默认值是从另一个对象继承的! 例如: class One(object): def __init__(self, my_list=[]): self.my_list = my_list one1 = One() print(one1.my_list) [] # empty list, what you'd expect. one1.my_list.append('hi') print(one1.my_list) ['hi'] # list with the n

python function default parameter is evaluated only once?

This question already has an answer here: “Least Astonishment” and the Mutable Default Argument 30 answers "The default value is only evaluated once" does not mean that a parameter with a default retains its value between invocations of the function. It means that the expression which you specify (the None part of def f(a, L=None) ) is evaluated once, and the object it results in i

python函数的默认参数只评估一次?

这个问题在这里已经有了答案: “最小的惊讶”和可变的默认参数30的答案 “默认值仅评估一次”并不意味着具有默认值的参数在函数调用之间保留其值。 这意味着您指定的表达式( def f(a, L=None)的None部分)被评估一次,并且它所导致的对象被存储在一个隐藏位置,并且如果该参数没有值是被重用的在通话时给予。 在每次调用时,参数仍会重置为值(默认值或不是)。 Python通过值将参数传递给函数; 所以对于对象来说,传递的

Optional parameters in Python functions and their default values

Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument I'm kind of confused about how optional parameters work in Python functions/methods. I have the following code block: >>> def F(a, b=[]): ... b.append(a) ... return b ... >>> F(0) [0] >>> F(1) [0, 1] >>> Why F(1) returns [0, 1] and not [1] ? I mean, what is ha

Python函数中的可选参数及其默认值

可能重复: Python中的“最小惊讶”:可变的默认参数 我对可选参数如何在Python函数/方法中工作感到困惑。 我有以下代码块: >>> def F(a, b=[]): ... b.append(a) ... return b ... >>> F(0) [0] >>> F(1) [0, 1] >>> 为什么F(1)返回[0, 1]而不是[1] ? 我的意思是, 里面发生了什么 ? 几年前,PyCon的优秀文档 - 解释了默认参数值。 但基本上,因为列表是可变对象,

Why is the empty dictionary a dangerous default value in Python?

This question already has an answer here: “Least Astonishment” and the Mutable Default Argument 30 answers Python methods: default parameter values are evaluated ONCE 3 answers It's dangerous only if your function will modify the argument. If you modify a default argument, it will persist until the next call, so your "empty" dict will start to contain values on calls other th

为什么空字典在Python中是一个危险的默认值?

这个问题在这里已经有了答案: “最小的惊讶”和可变的默认参数30的答案 Python方法:评估默认参数值一次3个答案 只有当你的函数修改参数时才是危险的。 如果您修改了默认参数,它将一直持续到下一次调用,因此您的“空白”字典将开始包含第一个调用以外的值。 是的,在这种情况下使用None既安全又传统。 我们来看一个例子: def f(value, key, hash={}): hash[value] = key return hash print f('a', 1) print

Python constructor and default value

This question already has an answer here: “Least Astonishment” and the Mutable Default Argument 30 answers Mutable default arguments don't generally do what you want. Instead, try this: class Node: def __init__(self, wordList=None, adjacencyList=None): if wordList is None: self.wordList = [] else: self.wordList = wordList if adjacen

Python的构造函数和默认值

这个问题在这里已经有了答案: “最小的惊讶”和可变的默认参数30的答案 可变的默认参数通常不会做你想要的。 相反,试试这个: class Node: def __init__(self, wordList=None, adjacencyList=None): if wordList is None: self.wordList = [] else: self.wordList = wordList if adjacencyList is None: self.adjacencyList = [] else:

Python class instance variable isolation

This question already has an answer here: “Least Astonishment” and the Mutable Default Argument 30 answers You just fell not in one, but in two Python well known "traps" for newcomers. This behavior is expected, and to fix it, you should change the beginning of your class declaration to: from typing import Optional class Test: def __init__(self, tags: Optional(dict)=None,

Python类实例变量隔离

这个问题在这里已经有了答案: “最小的惊讶”和可变的默认参数30的答案 你只是陷入了一个不为人所知的境地,但是却以两个着名的“陷阱”出现在新人面前。 这种行为是可以预料的,为了解决这个问题,你应该将类声明的开头改为: from typing import Optional class Test: def __init__(self, tags: Optional(dict)=None, fields: Optional(dict)=None): self.__tags = tags or {} self.__fields = fiel

Getting the length of an array in Python

In Python, is the following the only way to get the number of elements? arr.__len__() If so, why the strange syntax? my_list = [1,2,3,4,5] len(my_list) # 5 The same works for tuples: my_tuple = (1,2,3,4,5) len(my_tuple) # 5 And strings, which are really just arrays of characters: my_string = 'hello world' len(my_string) # 11 It was intentionally done this way so that lists, tuples and oth

在Python中获取数组的长度

在Python中,以下是获取元素数量的唯一方法吗? arr.__len__() 如果是这样,为什么奇怪的语法? my_list = [1,2,3,4,5] len(my_list) # 5 元组的相同作品: my_tuple = (1,2,3,4,5) len(my_tuple) # 5 字符串,它们只是字符数组: my_string = 'hello world' len(my_string) # 11 这是故意这样做的,以便列表,元组和其他容器类型不需要明确实现公共.length()方法,而只需检查实现了“魔术”的任何东西的len() __len__()方

String Object Representation in Python

This question already has an answer here: Difference between __str__ and __repr__? 21 answers __str__ (usually read dunder, for double under) is an instance method that is called whenever you run str(<object>) and returns the string representation of the object. str(foo) acts as a function trying to convert foo into a string. Note: There is also a __repr__() method which is fairl

Python中的字符串对象表示

这个问题在这里已经有了答案: __str__和__repr__之间的区别? 21个答案 __str__ (通常是读取dunder,用于double下)是一种实例方法,只要您运行str(<object>)并返回str(<object>)的字符串表示形式,就会调用它。 str(foo)作为一个函数试图将foo转换为字符串。 注意: 还有一个与__str__()非常相似的__repr__()方法,其主要区别是__repr__应该返回一个明确的字符串, __str__用于可读的字符串。 对于两