Comparing 2 class types

Jeremy Hylton jeremy at beopen.com
Fri Jul 7 11:35:14 EDT 2000


[Arinté wrote:]
>> How can you know if a 2 variables are different instances of the
>> same class? 
>> x = someclass()
>> y = someclass()
>> I tried is, type, and type(x)  is someclass, but none seem to work
>> unless I did it wrong.

[jepler.lnk at lnk.ispi.net (jepler epler) wrote:]
> isinstance()

isinstance is helpful, but not exactly what you're looking for.
Here's the doc string:

   isinstance(object, class-or-type) -> Boolean

   Return whether an object is an instance of a class or of a subclass
   thereof. With a type as second argument, return whether that is the
   object's type. 

so

instance(x, someclass) == 1
instance(y, someclass) == 1

If you want t compare the classes of x and y, use the __class__
attribute of the instance.

x.__class__ == y.__class__

This will only work if x and y have exactly the same class.  If you
have the following it won't work.

class otherclass(someclass):
	pass

x = someclass()
y = otherclass()

isinstance(x, someclass) == 1
isinstance(y, someclass) == 1
x.__class != y.__class__

Jeremy






More information about the Python-list mailing list