trouble understanding inheritance...
Steven D'Aprano
steve at REMOVEME.cybersource.com.au
Thu Aug 17 05:46:41 EDT 2006
On Wed, 16 Aug 2006 12:53:12 -0700, KraftDiner wrote:
>> > Well how does one select which class baseClass really is when you
>> > contruct the object?
>> > What am I missing?
>> >
>> > a = typeA()
>> > b = typeB()
>> > c = baseClass(a)
>>
>> a = typeA()
>> b = typeB()
>>
>> You're done. Stop there.
>>
> I can see that this might work...
> c = [a, b]
> for c in [a,b]:
> c.getName()
>
> but when does baseClass ever get used?
> Why did i even have to define it?
So that you don't duplicate code. That's it.
Here is a basic example. I have a class Foo with a method foo() that
returns "foo", and a second class Foos which is *almost* the same except
method foo() takes an argument and returns that number of foos.
class BaseClass():
def foo(self):
return "foo"
class Foo(BaseClass):
def foo(self):
return self.__class__.foo() # call the parent class method
class Foos(BaseClass):
def foo(self, n):
return self.__class__.foo() * n
Obviously in this case, there is no real need for BaseClass -- Foos could
inherit from Foo. But in more complex cases, you might need something like
this.
Hope this helps.
--
Steven D'Aprano
More information about the Python-list
mailing list