Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    # ...
like image 369
Cardano Avatar asked Jun 06 '15 12:06

Cardano


People also ask

How do you check if two objects are from the same class Python?

Both “is” and “==” are used for object comparison in Python. The operator “==” compares values of two objects, while “is” checks if two objects are same (In other words two references to same object).

Can multiple objects be created from the same class in Python?

A single class definition can be used to create multiple objects. As mentioned before, objects are independent. Changes made to one object generally do not affect the other objects representing the same class.


1 Answers

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()
like image 72
Marcus Müller Avatar answered Oct 09 '22 10:10

Marcus Müller