Isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。

isinstance() 与 type() 区别:

    type() 不会认为子类是一种父类类型,不考虑继承关系。

    isinstance() 会认为子类是一种父类类型,考虑继承关系。

    如果要判断两个类型是否相同推荐使用 isinstance()。
class A:
    pass
 
class B(A):
    pass
 
isinstance(A(), A)    # returns True
type(A()) == A        # returns True
isinstance(B(), A)    # returns True
type(B()) == A        # returns False

实际使用

     if not isinstance(value, int):
            raise ValueError('score must be an integer!')

class Student(object):

    def get_score(self):
         return self._score

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

相关文章:

  • 2021-07-28
  • 2021-12-22
  • 2022-02-27
  • 2022-12-23
  • 2021-05-16
  • 2021-12-09
  • 2021-06-05
  • 2021-12-12
猜你喜欢
  • 2022-12-23
  • 2022-02-11
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
相关资源
相似解决方案