Every object has a type
Every object has
type. This type determines the abilities of an object and by extension what an object represents.
Because in Python a type is also an object, the type of a type is the type
type
.
def printTypeOfType(obj):
type_of_obj = type(obj )
type_of_type = type(type_of_obj)
print(f'obj = {obj }')
print(f'type_of_obj = {type_of_obj }')
print(f'type_of_type = {type_of_type}')
print('')
printTypeOfType( 42 )
#
# obj = 42
# type_of_obj = <class 'int'>
# type_of_type = <class 'type'>
printTypeOfType( 99.9 )
#
# obj = 99.9
# type_of_obj = <class 'float'>
# type_of_type = <class 'type'>
printTypeOfType('Hello world')
#
# obj = Hello world
# type_of_obj = <class 'str'>
# type_of_type = <class 'type'>
printTypeOfType(printTypeOfType)
#
# obj = <function printTypeOfType at 0x000001F329B07F70>
# type_of_obj = <class 'function'>
# type_of_type = <class 'type'>
Internal C structures and mechanisms
All objects except type objects are always allocated on the heap, never on the stack.
The characteristics of a given type are stored in a
PyTypeObject
struct.
__dir__
If
obj
is an object that has a method named
__dir__
, this method will be called by
dir(obj)
.
This is typically used in conjuction with __getattr__()
and/or __getattribute__()
.