Cardano
Cardano

Reputation: 482

Python: asking if two objects are the same class

I have a class Animal and other animals inherit from it (e.q. Sheep, Wolf).
I want to check if two objects are the same class and if so, it should create new object of the same class and if they are not, they are fighting.

if x and y same object:
    #create new object
else:
    #fight

Is there a better method than isinstance?
Because, there will be more animals than just 2 and I think it wouldn't be efficient to do it like this:

if isinstance(x, Wolf)
    # ...

Upvotes: 25

Views: 20227

Answers (2)

Dinesh Kumar
Dinesh Kumar

Reputation: 27

if obj1==obj2: pass else: #do som

Upvotes: -6

Marcus Müller
Marcus Müller

Reputation: 36482

you can simply use

if type(x) == type(y):
    fight()

Python has a type system that allows you to do exactly that.

EDIT: as Martijn has pointed out, since Types only exist once in every runtime, you can use is instead of ==:

if type(x) is type(y):
    fight()

Upvotes: 33

Related Questions