NEWBIE: What's the instance name?

Peter Otten __peter__ at web.de
Mon Dec 29 04:27:52 EST 2003


Bengt Richter wrote:

> On 29 Dec 2003 00:36:09 -0800, danb_83 at yahoo.com (Dan Bishop) wrote:
> 
>>engsolnom at ipns.com wrote in message
>>news:<6q2vuv45lsah3epo9loa7l2tp9517makk4 at 4ax.com>...
>>> Hi,
>>> I've been using constructs(?) like the below.
>>> 
>>> def display(instance, start = None, end = None):
>>>     if instance.__class__.__name__ == 'UPCA':
>>
>>You might want to try the isinstance function.
> 
> <nit>
> 
> That's the usual idiom, but it should be noted that
> it's not exactly the same, e.g.,
> 
>  >>> class A: pass
>  ...
>  >>> class B(A): pass
>  ...
>  >>> a=A(); b=B()
>  >>> isinstance(a, A)
>  True
>  >>> isinstance(b, A)
>  True
>  >>> a.__class__.__name__ == 'A'
>  True
>  >>> b.__class__.__name__ == 'A'
>  False
> 
> That last, again, is not the same as
>  >>> isinstance(b, A)
>  True
> 
> </nit>

A few more lines to the fine print:

>>> class A: pass
...
>>> a1 = A()
>>> class A: pass
...
>>> a2 = A()
>>> a1.__class__.__name__ == "A"
True
>>> a2.__class__.__name__ == "A"
True
>>> a1.__class__ == A
False
>>> a2.__class__ == A
True
>>>

If you care about the class at all (and I think most of the time you
shouldn't) then compare classes, not names: 

instance.__class__ == Class 
instance.__class__ is Class


Peter






More information about the Python-list mailing list