super question

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Apr 8 17:38:48 CEST 2003


Lee Harr <missive at frontiernet.net> wrote in 
news:WRBka.134$jS3.16 at news02.roc.ny.frontiernet.net:

> Should this be showing
> Af
> Bf
> ?
> 
> How would I even get that output?  I know I can do:

Try this:
>>> class A(object):
	def f(self):
		print 'Af'
		if hasattr(super(A, self), 'f'):
			super(A, self).f()

			
>>> class B(object):
	def f(self):
		print 'Bf'
		if hasattr(super(B, self), 'f'):
			super(B, self).f()

			
>>> class C(A,B):
	def f(self):
		print 'Cf'
		super(C, self).f()

		
>>> c = C()
>>> c.f()
Cf
Af
Bf
>>> a = A()
>>> a.f()
Af
>>> 

Note that A.f() calls B.f() if self is a C, but doesn't call anything if 
self is an A.

Its easier if you want to propogate a function such as __init__ which you 
know is in the base class, because then you don't have to check for 
existence. Another way might be to define a class that is object with an 
empty f and use that as the base for both A and B.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list