Matthias Kaeppler wrote: > Hi, > > sorry for my ignorance, but after reading the Python tutorial on > python.org, I'm sort of, well surprised about the lack of OOP > capabilities in python. Honestly, I don't even see the point at all of > how OO actually works in Python. > > For one, is there any good reason why I should ever inherit from a > class? ^^ There is no functionality to check if a subclass correctly > implements an inherited interface and polymorphism seems to be missing > in Python as well. I kind of can't imagine in which circumstances > inheritance in Python helps. For example: > > class Base: > def foo(self): # I'd like to say that children must implement foo > pass > > class Child(Base): > pass # works > > Does inheritance in Python boil down to a mere code sharing? > > And how do I formulate polymorphism in Python? Example: > > class D1(Base): > def foo(self): > print "D1" > > class D2(Base): > def foo(self): > print "D2" > > obj = Base() # I want a base class reference which is polymorphic This line is redundant. You don't appear to want to actually create a Base object here, and the following code will ensure that you end up having an 'obj' variable anyway.
> if (<need D1>): > obj = D1() > else: > obj = D2() > OK. So now you have 'obj' referencing either a D1 or a D2. Both D1 and D2 objects have a foo() method, so here is polymorphism. There is no evidence of inheritance here though, because you chose to override the only method that they could have inherited from class Base. Now, if Base had also had a bar(self) method, both would have inherited that. Try this: class Base: def __init__(self): self.value = 0 def foo(self): print "Base", self.value def bar(self): self.value += 1 class D1(Base): def foo(self): print "D1", self.value class D2(Base): def foo(self): print "D2", self.value want1 = False if want1: obj = D1() else: obj = D2() obj.foo() obj.bar() obj.foo() Steve -- http://mail.python.org/mailman/listinfo/python-list