inheritance problem

Joe Mason joe at notcharles.ca
Thu Feb 19 06:03:56 EST 2004


In article <mailman.44.1077159655.27104.python-list at python.org>, Den Ivanov wrote:
> Example:
> ------------
> class c1:
>   def method1(self):
>     print 'class c1, method1'
>   def method2(self):
>     print 'class c1, method2'
>     self.method1()
> 
> class c2(c1):
>   def method1(self):
>     print 'class c2, method1'
>     c1.method2(self)
>   def method2(self):
>     print 'class c2, method2'
> 
> c = c2()
> c.method1()
> ------------
> i expect :
> class c2, method1
> class c1, method2
> class c1, method1

C++ and C# are the only languages I know of that are broken this way.

(Because it means their classes are not truly OO by default, that's why.
It causes confusion just like this.  I see the benefits of being able to
skip the virtual table lookup for speed, but that should be the
exception that needs to be turned on with a keyword, not the standard
behaviour.)

> but i get this:
> class c2, method1
> class c1, method2
> class c2, method1
> class c1, method2
> ...
> RuntimeError: maximum recursion depth exceeded
> 
> How fix this?

class c1:
  def base_method1(self):
    print 'class c1, method1'
  def method1(self):
    self.base_method1()
  def method2(self):
    print 'class c1, method2'
    self.base_method1()

Or

class c0:
  def method1(self):
    print 'class c1, method1'

class c1(c0):
  def method2(self):
    print 'class c1, method2'
    c0.method1(self)

Joe



More information about the Python-list mailing list