【问题标题】:What is the best way to check if an object is a subclass and NOT the base class [duplicate]检查对象是否是子类而不是基类的最佳方法是什么[重复]
【发布时间】:2021-07-17 18:24:11
【问题描述】:

让我们考虑以下代码 sn-p:

class Vehicle:
    pass

class Car(Vehicle):
    pass

my_car = Car()

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

输出:

True
True

现在,如果我的任务是判断 my_car 是否属于 Vehicle 类型而不属于 Car 类型,我该怎么做?

有没有一种聪明、简短、优雅的方法?

【问题讨论】:

  • inspect开头。
  • 如果my_carVehicle 的直接实例,那么type(my_car) is Vehicle。如果它是Vehicle 的间接实例,则为isinstance(my_car, Vehicle) and type(my_car) is not Vehicle
  • 你的标题和你在文中问的相反。

标签: python python-3.x object subclass


【解决方案1】:

使用isinstance()

isinstance(my_car, Vehicle) and not isinstance(my_car, Car)

【讨论】:

  • 但在我的情况下,两个 isinstance() 都是 True,所以完整的语句总是 False
  • 那是因为my_carCar。你说你想知道它是否不是Car
【解决方案2】:

如果my_carVehicle 的直接实例,则type(my_car) is Vehicle

如果它是Vehicle 的间接实例,则为isinstance(my_car, Vehicle) and type(my_car) is not Vehicle

【讨论】:

    【解决方案3】:

    请试试这个代码:

    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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 2010-11-15
      • 1970-01-01
      相关资源
      最近更新 更多