22

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)
    # ...
almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
Cardano
  • 452
  • 2
  • 8
  • 16

2 Answers2

28

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()
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • 8
    Classes are singletons, so it'd be more efficient to use `type(x) is type(y)`. – Martijn Pieters Jun 06 '15 at 12:25
  • you're right! @MartijnPieters, how comes you always notice when I'm sloppy? ;) – Marcus Müller Jun 06 '15 at 12:28
  • 1
    The *better* option is to delegate this task to the instances directly, where you know the type in the method. `def fight(self, other): if not isinstance(self, Wolf): return NotImplemented`, etc. – Martijn Pieters Jun 06 '15 at 12:32
  • 1
    @MartijnPieters: I'd generally agree, and it feels much more like C++ (which is what I probably like most about it); I'd even go as far as overloading the `+`/`__add__` operator! Also, if you derive all your animals from the same base class, you can simply check `if not isinstance(other, type(self))` and it will work as it should for all animals. In fact, this even feels like I should write a decorator, so that one can define methods that only take arguments of the same type as the containing class! – Marcus Müller Jun 06 '15 at 12:39
-4

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

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 19 '21 at 10:39
  • 3
    This comparison is far too strict; the question only asks for the objects to be instances of the same class, not for the objects to `__eq__` each other as is the case for this answer. – OrOrg Mar 22 '22 at 14:40