[Tutor] recursive problem

Roelof Wobben rwobben at hotmail.com
Sun Sep 12 09:59:44 CEST 2010




----------------------------------------
> From: rwobben at hotmail.com
> To: steve at pearwood.info
> Subject: RE: [Tutor] recursive problem
> Date: Sun, 12 Sep 2010 07:58:48 +0000
>
>
>
>
> ----------------------------------------
>> From: steve at pearwood.info
>> To: tutor at python.org
>> Date: Sun, 12 Sep 2010 10:10:53 +1000
>> Subject: Re: [Tutor] recursive problem
>>
>> On Sun, 12 Sep 2010 09:03:49 am Walter Prins wrote:
>>
>>> So, perhaps it's an idea to call dir() on a given object and see
>>> whether the object provides the necessary methods to function, e.g.
>>> __iter__, __delitem__, __setitem__ and friends?
>>
>> There's no need to do this:
>>
>> attributes = dir(obj)
>> if '__iter__' in attributes and '__len__' in attributes:
>> print "Quacks like a list"
>> else:
>> print "Not like a list"
>>
>>
>> when you can do this:
>>
>>
>> if hasattr(obj, '__iter__') and hasattr(obj, '__len__'):
>> print "Quacks like a list"
>> else:
>> print "Not like a list"
>>
>>
>> or this:
>>
>> try:
>> obj.__iter__
>> obj.__len__
>> except AttributeError:
>> print "Not like a list"
>> else:
>> print "Quacks like a list"
>>
>>
>> or even
>>
>> try:
>> iter(obj)
>> len(obj)
>> except TypeError:
>> print "Not like a list"
>> else:
>> print "Quacks like a list"
>>
>>
>> Where possible, the last version is to be preferred, because it doesn't
>> care about internal details which might change.
>>
>>
>>
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>

Oke,

This is to far for me.
Im only at chapter 11 and this stuff will be in chapter 13 and further.

Roelof 		 	   		  


More information about the Tutor mailing list