I'm a bit confused about types and classes in Python. For e.g. the following REPL conversation confuses me:
>>> class A: pass
...
>>> a = A()
>>> type(a)
<type 'instance'>
>>> a.__class__
<class __main__.A at 0xb770756c>
>>> type([])
<type 'list'>
>>> [].__class__
<type 'list'>
>>> type(list)
<type 'type'>
>>> list.__class__
<type 'type'>
>>> type(A)
<type 'classobj'>
>>> A.__class__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class A has no attribute '__class__'
__class__
for user defined classes?Any explanation/further reading which can clarify this behaviour would be much appreciated. TIA.
It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: Modifiers: A class can be public or has default access. class keyword: class keyword is used to create a class.
A user-defined class (or the class "object") is an instance of the class "type". So, we can see, that classes are created from type. In Python3 there is no difference between "classes" and "types". They are in most cases used as synonyms.
Python type() is a built-in function that returns the type of the objects/data elements stored in any data type or returns a new type object depending on the arguments passed to the function. The Python type() function prints what type of data structures are used to store the data elements in a program.
You're encountering the different behavior for new style classes versus classic classes. For further reading read this: Python Data Model. Specifically read the section on classes and the difference between new style and classic classes.
Try typing the following into your REPL:
class A: pass
class B(object): pass
and you'll see that you get different results. Here you're dealing with the difference between new style and old style classes. Using Python 2.6.1 here's what I get:
> type(A)
<type "classobj">
> type(B)
<type "type">
which tells you that lists are new style classes and not old style classes. We can further play around with things using list
as well:
> type(list)
<type "type">
same as our class B(object): pass
result. And also
> c = []
> type(c)
<type "list">
which is telling you about the instance of the object and not it's definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With