954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

super function

class x(object):
    def __init__(self):
        self.x=1

class y(x):
    def __init__(self):
        super(y, self).__init__()

what is it doing "super" function in here?

night_guard
Newbie Poster
3 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 

The super() function allows you to access methods in the parent x that are shadowed by methods of the same name in the child y.

In this case, y.__init__ wants to call x.__init__. But the problem is that y.__init__ clobbers __init__ in the namespace; that is, x.__init__ doesn't get inherited. SO, super(y, self) returns x, so that your code means this:

class x(object):
    def __init__(self):
        self.x=1

class y(x):
    def __init__(self):
        x.__init__(self)


Jeff

jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156
 

thanks

night_guard
Newbie Poster
3 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 
class x(object):
    def __init__(self):
        self.x=1

class z(object):
    def __init__(self):
        self.z=1

class y(x,z):
    def __init__(self):
        super(y, self).__init__()


And what is it doing "super" function in here?

Scorpiusix
Newbie Poster
1 post since Dec 2010
Reputation Points: 10
Solved Threads: 1
 
class x(object):
    def __init__(self):
        self.x=1

class z(object):
    def __init__(self):
        self.z=1

class y(x,z):
    def __init__(self):
        super(y, self).__init__()

And what is it doing "super" function in here?


It calls x.__init__():

class x(object):
    def __init__(self):
        print ("x.__init__()")
        self.x=1

class z(object):
    def __init__(self):
        print ("z.__init__()")
        self.z=1

class y(x,z):
    def __init__(self):
        super(y, self).__init__()

y()

"""my output -->
x.__init__()
"""

Super is not very useful. Call x.__init__() directly.

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You