[Python-3000] Builtin iterator type

Aaron Bingham bingham at cenix-bioscience.com
Mon Nov 20 10:47:59 CET 2006


Nick Coghlan wrote:

>Bill Janssen wrote:
>  
>
>>>Andrew Koenig wrote:
>>>      
>>>
>>>>In other words, whether or not we choose to define a family of types that
>>>>stand for particular abilities, I think we should not use inheritance as the
>>>>mechanism for specifying that a particular class has a particular ability.
>>>>I don't know what the mechanism should be, but it shouldn't be inheritance.
>>>>
>>>>Am I missing something?
>>>>        
>>>>
>>>It seems to me to be an excellent write-up of why using concrete classes for 
>>>interface definitions is potentially problematic.
>>>      
>>>
>>Huh?  Andrew pointed to exactly one "drawback", the inability to
>>disassociate an inherent characteristic of a type, its "typeness"
>>(which he refers to as ability-signalling), from a type.  I hardly see
>>that as problematic.
>>
>>Am *I* missing something?
>>    
>>
>
>Class inheritance implies a transitive relationship: if A is a B and B is a C, 
>then A is also a C. Not all characteristics of a type are necessarily 
>transitive in this fashion, so there are some things which cannot be 
>effectively expressed by means of class inheritance.
>
>Consider the classic example of a taxonomy of birds and the expression of the 
>property "this bird can fly" in a world containing emus, penguins and ostriches.
>
You seem to be imagining a class hierarchy like this:

class Bird1(object):
    def fly(self):
        # default implementation
        ....

class Finch1(Bird1):
        pass

class Ostrich1(Bird1):
   def fly(self):
       # oops, this doesn't make sense, and there is nothing we can do
       # except raise an error which will surprise clients expecting a 
generic Bird1
       raise RuntimeError("Ostriches can't fly")

However, of you know ahead of time that not all birds can fly you can 
design for this.

class FlightlessBirdError(Exception):
    """Raised when a flightless bird attempts to fly"""
    pass

class Bird2(object):
    def flightless(self):
        return False
    def fly(self):
        """Only valid if not flightless, otherwise raises 
FlightlessBirdError"""
        # default implementation
        if self.flightless():
            raise FlightlessBirdError()
        ...

class Finch2(Bird2):
    pass

class Ostrich2(Bird2):
    def flightless(self):
        return True

Now the possibility of flightlessness has been made explicit in the 
design and a client will not be surprised by failures caused by attempts 
to call fly() on a flightless bird.

Regards,

-- 
--------------------------------------------------------------------
Aaron Bingham
Senior Software Engineer
Cenix BioScience GmbH
--------------------------------------------------------------------



More information about the Python-3000 mailing list