3

When I am trying to check type of class declaration in Python 3 and Python 2, I get strange results, as followings show,

>>> #python 2.7.6
>>> class MyClass:
...     pass
... 
>>> type(MyClass)
<type 'classobj'>
>>> hasattr(MyClass, '__call__')
False

The type of MyClass in Python 2 is classobj and MyClass has no __call__ attribute. This is what I expect.

>>> #python 3.3.3
>>> class MyClass:
...     pass
... 
>>> type(MyClass)
<class 'type'>
>>> hasattr(MyClass, '__call__')
True

However, in Python 3, the type of MyClass is class 'type', and MyClass has __call__ attribute although I don't declare it within MyClass.

I guess the reason is that in Python 3, MyClass is a type, and type has __call__ attribute, am I right? and why Python 3 change the behavior of type function like this?

1 Answer 1

11

What changed is that all classes in 3.x are new-style classes by default. Your Python 2 classes did not inherit from object, so Python thought it was an old-style class.

In 2.7.5:

>>> class MyClass(object):
...   pass
... 
>>> type(MyClass)
<type 'type'>
>>> hasattr(MyClass, '__call__')
True
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your prompt reply! I have another question. If I set c = MyClass(), and callable(c) will return false, but hasattr(MyClass, '__call__') returns true. So why callable(c) returns false?
@mitchelllc You did not override the default __call__, so callable(c) shows as False. However, if you inherit from a function, it will be callable() by default.
@tyteen4a03 well, I am a little confused. callable(c) returns false because I don't override the default __call__, but why hasattr(MyClass, '__call__') return true? Big thanks!
@mitchelllc You're mixing up the class and its instances. callable(MyClass) is true. hasattr(c, '__call__') is false.
Hi @delnan, thank you for the point. I find these words help me understand it. classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__() method. from docs.python.org/2/library/functions.html#callable

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.