super behavior

T

TP

Hi,

Hereafter is an example using super.
At the execution, we obtain:

coucou
init_coucou2
coucou1
coucou2
Traceback (most recent call last):
File "essai_heritage.py", line 34, in <module>
print b.a
AttributeError: 'coucou' object has no attribute 'a'

Why Python does not enter in the __init__ method of coucou1?
If I replace the two lines using "super" by the two following lines, it
works perfectly:

coucou1.__init__( self )
coucou2.__init__( self )

##########
class coucou1( object ):

def __init__( self
, a = 1 ):
self.a = a
print "init_coucou1"

def print_coucou1( self ):
print "coucou1"


class coucou2( object ):

def __init__( self
, b = 2 ):
self.b = b
print "init_coucou2"

def print_coucou2( self ):
print "coucou2"


class coucou( coucou1, coucou2 ):

def __init__( self ):

print "coucou"
super( coucou1, self ).__init__( )
super( coucou2, self ).__init__( )

b = coucou()
b.print_coucou1()
b.print_coucou2()
print b.a
print b.b
##################
--
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
 
D

Diez B. Roggisch

TP said:
Hi,

Hereafter is an example using super.
At the execution, we obtain:

coucou
init_coucou2
coucou1
coucou2
Traceback (most recent call last):
File "essai_heritage.py", line 34, in <module>
print b.a
AttributeError: 'coucou' object has no attribute 'a'

Why Python does not enter in the __init__ method of coucou1?

Because you use super wrong. It's not supposed to be called with a
superclass, but with the current class. And each class needs to call
super itself in it's own __init__-method.

Like this:


class coucou1( object ):

def __init__( self
, a = 1 ):
self.a = a
print "init_coucou1"
super( coucou1, self ).__init__( )

def print_coucou1( self ):
print "coucou1"


class coucou2( object ):

def __init__( self
, b = 2 ):
self.b = b
print "init_coucou2"
super( coucou2, self ).__init__( )

def print_coucou2( self ):
print "coucou2"


class coucou( coucou1, coucou2 ):

def __init__( self ):
print "coucou"
super( coucou, self ).__init__( )

b = coucou()
b.print_coucou1()
b.print_coucou2()
print b.a
print b.b


Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,130
Members
46,689
Latest member
liammiller

Latest Threads

Top