![]() |
Default values of arguments with the same id - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Default values of arguments with the same id (/thread-31287.html) |
Default values of arguments with the same id - DrVictor - Dec-02-2020 class test: def __init__(self,val=[]): self.val=val a=test() b=test() print(id(a.val)==id(b.val)) #TrueI noticed that the default value of the arguments has the same id as other instances. And by changing that value, it changes for other instances. a.val+=[12] print(b.val) # [12]Is this normal for you? RE: Default values of arguments with the same id - stranac - Dec-02-2020 Ah, the good old mutable defaults... https://python-forum.io/Thread-Basic-Various-Python-Gotchas has an explanation of what's going on. Search for "empty list". RE: Default values of arguments with the same id - DrVictor - Dec-02-2020 (Dec-02-2020, 02:16 PM)stranac Wrote: Ah, the good old mutable defaults...Thank you for your answer. According to you, I searched the internet. And I used the following solution class test: def __init__(self,val=None): if val==None:val=[] self.val=valWriting the third line sounds a little silly but I have to.This reduces the readability of Python. I think for other people with a different id is more useful than the same id. RE: Default values of arguments with the same id - deanhystad - Dec-02-2020 class test: def __init__(self,val=None): self.val = [] if val is None else valI think "None" is the only default value that should be used for methods. When subclassing I kept running into problems with default arguments hiding that no value had been provided. In the example below I wanted b to "inherit" a's default value. class a: def __init__(self, value=2): self.value = value def __repr__(self): return str(self.value) class b(a): def __init__(self, value=None): # Want superclass to provide default super().__init__(value) print(b(), b(5)) The inheritance works if I use None in the method signature and set the value in the method body.class a: def __init__(self, value=None): self.value = 2 if value is None else value def __repr__(self): return str(self.value) class b(a): def __init__(self, value=None): # Want superclass to provide default super().__init__(value) print(b(), b(5))
|