Comparing two class types in python

前端 未结 4 2107
时光取名叫无心
时光取名叫无心 2021-02-20 12:07

I have two classes defined in a module classes.py:

class ClassA(object):
    pass

class ClassB(object):
    pass

And in another m

4条回答
  •  [愿得一人]
    2021-02-20 12:58

    Explanation

    This is why your comparison doesn't work as expected

    >>> class ClassA(object):
    ...     pass
    ... 
    >>> class ClassB(object):
    ...     pass
    ... 
    >>> type(ClassB)
     
    >>> type(ClassA)
     
    >>> type(ClassA) == type(ClassB)
    True
    

    But why do ClassA and ClassB have the same type type? Quoting the docs:

    By default, classes are constructed using type(). The class body is executed in a new namespace and the class name is bound locally to the result of type(name, bases, namespace).

    Example:

    >>> ClassB
    
    >>> type('ClassB', (), {})
    
    >>> type(ClassB)
    
    >>> type(type('ClassB', (), {}))
    
    

    Getting the type of ClassB is exactly the same as getting the type of type('ClassB', (), {}), which is type.

    Solutions

    Compare them directly (w/out using the type() function):

    >>> ClassA
    
    >>> ClassB
    
    >>> ClassA == ClassB
    False
    

    or initialize them and compare the types of their objects:

    >>> a = ClassA()
    >>> b = ClassB()
    >>> type(a) 
    
    >>> type(b) 
    
    >>> type(a) == type(b)
    False
    

    FWIW you can also use is in place of == (for classes).

提交回复
热议问题