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?

2
  • 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. Commented Apr 23, 2017 at 10:21
  • @Rawing Ur comment makes more sense. :D Commented Apr 23, 2017 at 11:42

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.