0

Look at the following example.

>>> class X:
        pass 
>>> Y = X
>>> X
<class '__main__.X'>
>>> Y
<class '__main__.X'>
>>> Y == X
True
>>> Y is X
True

The above code is understandable. But, look at the below one.

>>> X = type('X', (), {})
>>> Y = type('X', (), {})
>>> X
<class '__main__.X'>
>>> Y
<class '__main__.X'>
>>> X == Y        # Shouldn't this be True??
False
>>> X is Y
False

Here X is Y == False is as expected. But how come X == Y is False? They both are of same class type, ain't they?

RatDon
  • 3,403
  • 8
  • 43
  • 85
  • 2
    Short answer to the question: Classes can't be compared with `==` because nobody implemented that feature; and the standard behaviour of `a == b` (if not overriden) is to return `a is b`. – Aran-Fey Apr 23 '17 at 10:21
  • @Rawing Ur comment makes more sense. :D – RatDon Apr 23 '17 at 11:42

2 Answers2

1

According to the docs: '... With three arguments, return a new type object'.

>>> X1 = type('X', (), {})
>>> Y1 = type('X', (), {})
>>> id(X1) == id(Y1)
False

Whereas the first example Y 'references' X:

>>> class X:
...     pass
... 
>>> Y = X
>>> id(X) == id(Y)
True
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
1

When you use the class statement, two things happen. First, a class is created, with the name you specify. That is, the class has a __name__ attribute with that string as its value. Second, that class is assigned to that name as a variable.

>>> class X:
        pass 
>>> X.__name__
'X'
>>> Y = X
>>> Y.__name__
'X'

When you print a class, it's showing you the __name__ value:

>>> X
<class '__main__.X'>
>>> Y
<class '__main__.X'>

As you've seen when you assign X to Y, the name of the variable, and the name of the class, can be different.

When you create classes with type, you make a new distinct class every time. You can have two classes with the same __name__, each assigned to different variable. That's what you did here:

>>> X = type('X', (), {})
>>> Y = type('X', (), {})
>>> X
<class '__main__.X'>
>>> Y
<class '__main__.X'>
>>> X.__name__
'X'
>>> Y.__name__
'X'
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662