class Pen(object):
def __init__(self, mean_radius = None, length = None):
self.usage = "Is used to apply ink trails to drawing surfaces"
self.mean_radius = mean_radius
self.length = length
class FountainPen(Pen):
def __init__(self, manufacturer = "Waterman", *args, **kwargs):
Pen.__init__(self, *args, **kwargs)
self.manufacturer = manufacturer
self.cartridge_state = "non-empty"
>>> instance_FP = FountainPen(5, 1)
>>> instance_FP.mean_radius
>>> print instance_FP.mean_radius
1
>>> print instance_FP.length
None
What happens with the integer 5 being passed as an argument in the instantiation of FountainPen?
Why does print instance_FP.mean_radius return 1 and not 5?
You have to think it like that:
*argsand**kwargs“eat” all the positional/keyword arguments left by the “regular” arguments that precede them. If you put them in the end, they will only get whatever couldn’t fit the “regular arguments”.So, when you write
FountainPen(5,1)what happens is thatFountainPen.__init__gets called like this:selfis set to the newly created instance;manufacturergets the first argument, which is 5;*args“eats” all the remaining positional arguments, i.e. just1; soargsis now set to[1];*kwargswould eat any keyword argument left, but there’s none, so it becomes{}.It’s then clear that
Pen.__init__is called with just1as argument (besidesself), andlengthremains set to its default value (None).