My goal is to set default values of mutable type (list) for several object attributes. Per the discussion here, I set the default values of those attributes to None
in the arguments of __init__
, then I assign them the value []
in __init__
if they took on their default value. Here's a representation of this:
class Wat(object):
def __init__(self, arg1=None, arg2=None, arg3=None):
for arg in arg1, arg2, arg3:
if arg == None:
arg = []
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def give(self, thing):
self.arg1.append(thing)
self.arg2.append(thing)
self.arg3.append(thing)
wat = Wat()
wat.give(5)
However, this throws the following exception:
AttributeError: 'NoneType' object has no attribute 'append'
.
I don't see how wat.arg1
, wat.arg2
, and wat.arg3
can still have type None
at the time wat.give(5)
is called -- they should have been reassigned to []
in __init__
. It must have something to do with the way I coded the assignment, because this works:
class Wat(object):
def __init__(self, arg1=None, arg2=None, arg3=None):
if arg1 == None:
arg1 = []
if arg2 == None:
arg2 = []
if arg3 == None:
arg3 = []
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def give(self, thing):
self.arg1.append(thing)
self.arg2.append(thing)
self.arg3.append(thing)
wat = Wat()
wat.give(5)
To my mind, the two syntaxes are functionally equivalent, but you can imagine how the latter syntax becomes very tedious and aesthetically displeasing as the number of arguments assigned in this way increases.
What's wrong with the former syntax? How can I fix it? Thanks.
EDIT: Several of you have identified the problem, but I still don't have a satisfying solution. @roippi suggested an efficient method for assigning the variables one at a time, but suppose I have 100 of these variables. How do I do this assignment in the fewest lines of code? That was the original purpose of the loop. Thanks folks.