1

let's consider the following code snippet:

class Vehicle:
    pass

class Car(Vehicle):
    pass

my_car = Car()

print(issubclass(type(my_car), Car))
print(issubclass(type(my_car), Vehicle))

Output:

True
True

Now if my task was to tell if my_car is of type Vehicle but not of type Car, how would I do that?

Is there a smart, short, elegant way for this?

toto290
  • 29
  • 5
  • Start with [inspect](https://docs.python.org/3/library/inspect.html). – jarmod Apr 23 '21 at 14:26
  • If `my_car` is a direct instance of `Vehicle` then `type(my_car) is Vehicle`. If it is an indirect instance of `Vehicle` then `isinstance(my_car, Vehicle) and type(my_car) is not Vehicle`. – khelwood Apr 23 '21 at 14:28
  • Your title is the opposite of what you ask in the text. – Barmar Apr 23 '21 at 14:43

3 Answers3

2

If my_car is a direct instance of Vehicle then type(my_car) is Vehicle.

If it is an indirect instance of Vehicle then isinstance(my_car, Vehicle) and type(my_car) is not Vehicle.

khelwood
  • 55,782
  • 14
  • 81
  • 108
1

Use isinstance()

isinstance(my_car, Vehicle) and not isinstance(my_car, Car)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Please try this code:

class Vehicle:
    pass

class Car(Vehicle):
    pass

my_car = Car()


if type(my_car) == Vehicle and type(my_car) != Car:
    print("my_car is Vehicle")
elif type(my_car) != Vehicle and type(my_car) == Car:
    print("my_car is Car")
timhu
  • 98
  • 4