At Thursday 24/8/2006 19:51, Chaz Ginger wrote:

>> I was writing some code that used someone else class as a subclass. He
>> wrote me to tell me that using his class as a subclass was incorrect. I
>> am wondering under what conditions, if ever, does a class using a
>> subclass not work.
>>
>> class B1(A);
>>   def __init__(self,a1,a2) :
>>         self.c = a1
>>         A.__init__(self,ag)
>>
>> class B2:
>>   def __init__(self,a1,a2):
>>         self.c = a1
>>         self.t = A(a2)
>>
>>   def bar(self) :
>>         self.t.bar()
>>
>> Other than the obvious difference of B2 having an attribute 't', I can't
>> see any other obvious differences. Is there something I am missing?
>
> Look any OO book for the difference between 'inheritance' and
> 'delegation'. In short, you should inherit when B 'is an' A (a Car is a
> Vehicle), and delegate/compose in other cases (a Car has an Engine; or
> more precisely, a Car instance has an Engine instance).

I was wondering more about the mechanics of Python: when does B1 show
different characteristics than B2  (forgoing the obvious simple things,
like 't' above).
Inheritance implies that *all* methods/attributes of A are exposed by B1; it's directly supported by the language. Inheritance is usually a relationship between classes. If you add a method foo() to A, instances of B1 automatically have it. A B1 instance "is an" A instance. Using delegation, you have to delegate the desired method calls yourself (but there are ways to do that automatically, too). Delegation is a relationship between instances. If you add a method foo() to A, you have to add it to B2 too. A B2 instance "is not an" A instance.

Once again you answered all the generic things about classes. I could have taken that from a book on OO. All well and good but not specifically addressed to the question I asked. Please read what I wrote. I am more interested in knowing specifics about the Python implementation and if there are any "gotchas" that would make B1 different from B2.

Please stay on the list.

b1 = B1()
b2 = B2()
isinstance(b1, A) -> True
isinstance(b2, A) -> False

For any other method defined in A, say foo:
b1.foo() is OK
b2.foo() raises AttributeError

So you decide to override foo() too (in both implementations, B1 and B2)
Let's say, A.bar() calls self.foo()
b1.bar() calls B1.foo on b1
b2.bar() calls A.foo on t - B2.foo is *not* called.

Enough examples? Inheritance and delegation are *not* the same thing. Anyway, none of these examples is very Python-specific.



Gabriel Genellina
Softlab SRL

        
p5.vert.ukl.yahoo.com uncompressed Fri Aug 25 01:27:04 GMT 2006
                
__________________________________________________ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to