gpt4 book ai didi

python - 类方法中的默认参数不是唯一的python

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:36 25 4
gpt4 key购买 nike

我在 python 类中的默认参数方面遇到问题。似乎当未给出参数时,默认链接到类的所有实例的同一对象。示例:

class My_class:
def __init__(self,options=[]):
self.options = options

class1 = My_class()
class2 = My_class()

class2.options.append('something')
print(class1.options)

这将打印:

['something']

如何确保类的每个实例都有一个唯一的选项列表,而不是对同一对象的引用。例如,我可以这样做:

    def __init__(self,options=None):
if options is None:
options = []
self.options = options

但是,这对我来说并不正确。所以我的问题是是否有更好的方法来做到这一点,并且有人向我解释最初的行为,因为我知道发生了什么,但我不完全明白为什么

最佳答案

这是最常见的之一 python gotchas .

Python’s default arguments are evaluated once when the function is defined, not each time the function is called. This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well. Your second variant with None is just fine and is widely used in python.

关于python - 类方法中的默认参数不是唯一的python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47392998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com