[Tutor] How arguments to the super() function works?

Mats Wichmann mats at wichmann.us
Sun May 19 11:45:34 EDT 2019


On 5/19/19 12:28 AM, Arup Rakshit wrote:
> 
>> On 19-May-2019, at 4:46 AM, Mark Lawrence <breamoreboy at gmail.com> wrote:
>>
>> On 18/05/2019 17:21, Arup Rakshit wrote:
>>> I am writing an Flask app following a book, where a piece of python concept I am not getting how it works. Code is:
>>> class Role(db.Model):
>>>     __tablename__ = 'roles'
>>>     id = db.Column(db.Integer, primary_key=True)
>>>     name = db.Column(db.String(64), unique=True)
>>>     default = db.Column(db.Boolean, default=False, index=True)
>>>     permissions = db.Column(db.Integer)
>>>     users = db.relationship('User', backref='role', lazy='dynamic')
>>>     def __init__(self, **kwargs):
>>>         super(Role, self).__init__(**kwargs)
>>>         if self.permissions is None:
>>>             self.permissions = 0
>>> Here, why super(Role, self).__init__(**kwargs) is used instead of super().__init__(**kwargs) ? What that Role and self argument is instructing the super() ?
>>> Thanks,
>>> Arup Rakshit
>>> ar at zeit.io
>>
>> Please check this https://www.youtube.com/watch?v=EiOglTERPEo out.  If that doesn't answer your question please ask again.
>>
> 
> 
> Hello Mark,
> 
> Thanks for sharing the link. Just finished the talk. Little better now about how super uses the MRO.
> 
> class Dad:
>     def can_i_take_your_car(self):
>         print("No...")
> 
> class Mom(Dad):
>     def can_i_take_your_car(self):
>         print("Asking your dad...")
> 
> class Victor(Mom, Dad):
>     def can_i_take_your_car(self):
>         print("Asking mom...")
> 
> class Pinki(Mom, Dad):
>     def can_i_take_your_car(self):
>         print("I need it today..")
> 
> class Debu(Pinki, Victor):
>     def can_i_take_your_car(self):
>         super(Victor, self).can_i_take_your_car()
> 
> In this piece of code:
> 
> print(Debu().can_i_take_your_car())
> 
> Why the above call prints "Asking your dad…” but not " print("Asking mom…”)” although can_i_take_your_car is defined inside the class Victor ?

Because that's what you asked for?

in Debu you asked to call the method through the object obtained by
calling super on Victor, and that resolves to Mom per the MRO.  help()
gets that for you, but you can also check it programmatically:

print(Victor.__mro__)

(<class '__main__.Victor'>, <class '__main__.Mom'>, <class
'__main__.Dad'>, <class 'object'>)


you can also print the method it would resolve to, change class Debu to:

class Debu(Pinki, Victor):
    def can_i_take_your_car(self):
        print(super(Victor, self).can_i_take_your_car)  # note this is
not a call
        super(Victor, self).can_i_take_your_car()

and you can see how it resolves:

<bound method Mom.can_i_take_your_car of <__main__.Debu object at
0x7ff8bdc6a9e8>>
Asking your dad...




More information about the Tutor mailing list