class instance type comparisons, like isa() 
Author Message
 class instance type comparisons, like isa()

Quote:

> I have a base class B and two subclasses C and D. I want to determine whether
> a given instance is of type C or D. Is there a built-it way in python can I
> do this, or do I need to implement it myself in the classes?

Use the instance attribute __class__, like so:

class B:
    pass

class C(B):
    pass

class D(B):
    pass

b = B()
c = C()
d = D()

print b.__class__ == C
print b.__class__ == B
print c.__class__ == C
print c.__class__ == B

I hope you get the idea. You might also want to look into the issubclass()
function. It is a built in function described in the Python Library
Reference guide.



Mon, 23 Apr 2001 03:00:00 GMT  
 class instance type comparisons, like isa()
you can also use isinstance to test if an object is an instance of some
class:

isinstance(b,C)
isinstance(c,C)


Quote:

>> I have a base class B and two subclasses C and D. I want to determine
whether
>> a given instance is of type C or D. Is there a built-it way in python can
I
>> do this, or do I need to implement it myself in the classes?

>Use the instance attribute __class__, like so:

>class B:
>    pass

>class C(B):
>    pass

>class D(B):
>    pass

>b = B()
>c = C()
>d = D()

>print b.__class__ == C
>print b.__class__ == B
>print c.__class__ == C
>print c.__class__ == B

>I hope you get the idea. You might also want to look into the issubclass()
>function. It is a built in function described in the Python Library
>Reference guide.



Tue, 24 Apr 2001 03:00:00 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. instance isA class -- how?

2. instances of classes and instances of instances

3. determining method type (instance, static, class)

4. Instance of class as a class

5. Can a class instance also be a class?

6. Classes - instance/class, methods/members, inheritance and best p ractices

7. Comparing class instance with class

8. Problem with calling instance of one class from another class

9. repeated class redefinition and update-instance-for-redefined-class

10. type(type) is an object, not an instance

11. Classes - instance/class, methods/members, inheritance and be st practices

12. Conflict Between Class-as-Module and Class-as-Type (long)

 

 
Powered by phpBB® Forum Software