def __init__(self):
self.score=[]
def __init__(self,score=[]):
self.score=score
def __init__(self,score):
self.score=[]
Can you please explain what happens behind the scenes? TIA.
def __init__(self):
self.score=[]
def __init__(self,score=[]):
self.score=score
def __init__(self,score):
self.score=[]
Can you please explain what happens behind the scenes? TIA.
def init(self):
self.score=[]
self.score
is always initialized to an empty list.
def init(self,score=[]):
self.score=score
The caller can pass in an optional list parameter. If they don't, self.score
is initialized to an empty list once, when the function is defined. (See Common Gotchas: Mutable Default Arguments for why this is a bad idea.)
def init(self,score):
self.score=[]
The caller must pass in a list parameter (normally, that would be assigned to self.score
, but you're throwing that value out and setting self.score
to an empty list). The third example probably should be:
def init(self, score):
self.score = score
In the first one, you always assign [] to the objects score variable. In the second one, you can construct the object with or without the score value, for example if you do obj = object([1,2,3]), then it will have score equal to [1,2,3], but you can also call it without the score argument, like obj = object(), and it will have score equal to []. In the third example, you have to create with the score argument, but it will be ignored, as it is not assigned to the self.score variable.
score
in function header is a local variable
def init(self,score):
and here it is an instance attribute
self.score=[]
The first and last methods have exactly the same effect: assign an empty list to the instance attribute score
. For some strange reason, the third one requires an extra positional parameter score
, which is not used.
The middle one creates and reserves a default value for the parameter score
; at parse time, this value is an empty list. Any instantiation that omits that argument gets assigned the reserved list. The danger here is that these instantiations will all refer to the same list: a change to the score
attribute in one will be reflected in all of the other objects that used the default value.