【问题标题】:How to check whether a variable is a class or not?如何检查变量是否是类?
【发布时间】:2008-12-28 03:08:05
【问题描述】:

我想知道如何检查变量是否是类(不是实例!)。

我尝试使用函数isinstance(object, class_or_type_or_tuple) 来执行此操作,但我不知道类将具有什么类型。

例如在下面的代码中

class Foo: pass  
isinstance(Foo, **???**) # i want to make this return True.

我尝试将“class”替换为???,但我意识到class是python中的关键字。

【问题讨论】:

    标签: python reflection


    【解决方案1】:

    更好的是:使用inspect.isclass 函数。

    >>> import inspect
    >>> class X(object):
    ...     pass
    ... 
    >>> inspect.isclass(X)
    True
    
    >>> x = X()
    >>> isinstance(x, X)
    True
    >>> inspect.isclass(x)
    False
    

    【讨论】:

    • 如果要检查的对象是类实例,您还希望inspect.isclass返回True,请使用inspect.isclass(type(Myclass()))
    • @michaelmeyer type(whatever) 总是返回一个类对象,所以这个检查是多余的。如果没有,就无法实例化whatever,因此您一开始就无法执行检查。
    • 对我不起作用。将python3与snakemake一起使用,type(snakemake.utils)返回<class 'module'>inspect.isclass(snakemake.utils)返回False
    • 那是因为snakemake.util 是一个模块而不是一个类?
    • @tedtoal type(snakemake.utils) 返回<class 'module'> 表示snakemake.utilsmodule 类的object。所以isclass() 的行为是正确的。
    【解决方案2】:
    >>> class X(object):
    ...     pass
    ... 
    >>> type(X)
    <type 'type'>
    >>> isinstance(X,type)
    True
    

    【讨论】:

    • 嗯...不错的答案,但是当我在我的 Foo 类上键入(Foo)时,它显示的是 而不是 。我假设差异来自 X 是从对象继承的事实,但 Foo 不是。是否有任何其他差异由此产生?谢谢。
    • 它不适用于老式类:'class Old:pass' 'isinstance(Old, type) == False',但 inspect.isclass(Old) == True
    • @jeeyoungk:您不是“假设差异来自...”,您实际上是在代码中阅读。对象的子类(“新样式”)具有所需的属性,正如您在此处看到的那样。
    • 这里是提示——因为这适用于新式类,所以不要使用旧式类。使用旧式类没有意义。
    • isinstance(e, f) E为实例化对象,F为类对象。
    【解决方案3】:

    inspect.isclass 可能是最好的解决方案,而且很容易看出它是如何实际实现的

    def isclass(object):
        """Return true if the object is a class.
    
        Class objects provide these attributes:
            __doc__         documentation string
            __module__      name of module in which this class was defined"""
        return isinstance(object, (type, types.ClassType))
    

    【讨论】:

    • 记得import types
    • types.ClassType 在 Python 3 中不再需要(并且已被删除)。
    • 这根本不适用于新样式类......即使在 python 2 中。不要单独使用这个解决方案
    • 这是 Python 2 的实现,它必须处理旧式和新式类。 Python 3 将其简化为isinstance(object, type)。请注意,intliststr 等对象也是 类,因此您不能使用它来区分Python 中定义的自定义类在 C 代码中定义的内置类
    • 不要将你的论点称为object。这掩盖了突出的内置名称object
    【解决方案4】:
    isinstance(X, type)
    

    如果X 是类,则返回True,否则返回False

    【讨论】:

    • 我得到 False,即使 X 是一个类。
    • 这仅适用于新样式类。旧样式类的类型为“classobj”。因此,如果您使用的是旧式类,您可以这样做: import types isinstance(X, types.ClassType)
    • 这似乎和S. Lott's answer 一样,都大了四年。
    【解决方案5】:

    此检查与 Python 2.x 和 Python 3.x 兼容。

    import six
    isinstance(obj, six.class_types)
    

    这基本上是一个包装函数,执行与 andrea_crotti 答案中相同的检查。

    例子:

    >>> import datetime
    >>> isinstance(datetime.date, six.class_types)
    >>> True
    >>> isinstance(datetime.date.min, six.class_types)
    >>> False
    

    【讨论】:

      【解决方案6】:

      Benjamin Peterson 关于在这项工作中使用inspect.isclass() 是正确的。 但请注意,您可以使用内置函数 issubclass 测试 Class 对象是否是特定的 Class,因此隐含的是 Class。 根据您的用例,这可能更符合 Python 风格。

      from typing import Type, Any
      def isclass(cl: Type[Any]):
          try:
              return issubclass(cl, cl)
          except TypeError:
              return False
      

      然后可以这样使用:

      >>> class X():
      ...     pass
      ... 
      >>> isclass(X)
      True
      >>> isclass(X())
      False
      

      【讨论】:

        【解决方案7】:

        class Foo: 称为旧式类,class X(object): 称为新式类。

        检查此What is the difference between old style and new style classes in Python? 。推荐新款式。阅读“unifying types and classes

        【讨论】:

        • 这应该是评论吧?
        【解决方案8】:

        最简单的方法是使用投票最多的答案中发布的inspect.isclass
        实现细节可以在python2 inspectpython3 inspect找到。
        新式班:isinstance(object, type)
        旧式课程:isinstance(object, types.ClassType)
        em,对于老式类,它使用types.ClassType,这是来自types.py的代码:

        class _C:
            def _m(self): pass
        ClassType = type(_C)
        

        【讨论】:

          【解决方案9】:

          还有另一种检查方法:

          import inspect
          
          class cls():
               print(None)
          
          inspect.isclass(cls)
          

          参考:https://www.kite.com/python/docs/inspect.isclass

          【讨论】:

            【解决方案10】:

            好吧,inspect.isclass 不适合我,试试这个

            class foo:
                pass
            
            var = foo()
            
            if str(type(var)).split(".")[0] == "<class '__main__":
                print("this is a class")
            else:
                print(str(type(var)).split(".")[0])
            

            所以基本上,type(var)&lt;class 'a type'&gt;

            示例:&lt;class 'int' 但是,当var 是一个类时,它会出现类似&lt;class '__main__.classname'&gt;

            因此我们将字符串拆分为&lt;class '__main__,然后使用if 进行比较,如果字符串完美匹配,那么它就是一个类

            【讨论】:

            • 我认为我没有得到任何投票,哈哈
            【解决方案11】:

            在某些情况下(取决于您的系统),一个简单的测试是查看您的变量是否具有 __module__ 属性。

            if getattr(my_variable,'__module__', None):
                print(my_variable, ".__module__ is ",my_variable.__module__)
            else:
                print(my_variable,' has no __module__.')
            

            int、float、dict、list、str 等没有 __module__

            【讨论】:

              【解决方案12】:

              这里已经有一些可行的解决方案,但这里有另一个:

              >>> import types
              >>> class Dummy: pass
              >>> type(Dummy) is types.ClassType
              True
              

              【讨论】:

              • types.ClassType 在 Python 3 中被删除
              猜你喜欢
              • 2015-08-25
              • 2011-03-26
              • 2013-03-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-04-19
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多