A Python script can find out about the type, class, attributes and methods of an object. This is referred to asreflection orintrospection. See alsoMetaclasses.
Reflection-enabling functions include type(), isinstance(), callable(), dir() and getattr().
The type method enables to find out about the type of an object. The following tests return True:
The type function disregards class inheritance: "type(3) is object" yields False while "isinstance(3, object)" yields True.
Links:
Determines whether an object is an instance of a type or class.
The following tests return True:
Note that isinstance provides a weaker condition than a comparison using#Type.
Function isinstance and a user-defined class:
classPlant:pass# Dummy classclassTree(Plant):pass# Dummy class derived from Planttree=Tree()# A new instance of Tree classprint(isinstance(tree,Tree))# Trueprint(isinstance(tree,Plant))# Trueprint(isinstance(tree,object))# Trueprint(type(tree)isTree)# Trueprint(type(tree).__name__=="instance")# Falseprint(tree.__class__.__name__=="Tree")# True
Links:
Determines whether a class is a subclass of another class. Pertains to classes, not their instances.
classPlant:pass# Dummy classclassTree(Plant):pass# Dummy class derived from Planttree=Tree()# A new instance of Tree classprint(issubclass(Tree,Plant))# Trueprint(issubclass(Tree,object))# False in Python 2print(issubclass(int,object))# Trueprint(issubclass(bool,int))# Trueprint(issubclass(int,int))# Trueprint(issubclass(tree,Plant))# Error - tree is not a class
Links:
Duck typing provides an indirect means of reflection. It is a technique consisting in using an object as if it was of the requested type, while catching exceptions resulting from the object not supporting some of the features of the class or type.
Links:
For an object, determines whether it can be called. A class can be made callable by providing a __call__() method.
Examples:
Links:
Returns the list of names of attributes of an object, which includes methods. Is somewhat heuristic and possibly incomplete, as per python.org.
Examples:
Links:
Returns the value of an attribute of an object, given the attribute name passed as a string.
An example:
The list of attributes of an object can be obtained using#Dir.
Links:
A list of Python keywords can be obtained from Python:
importkeywordpykeywords=keyword.kwlistprint(keyword.iskeyword("if"))# Trueprint(keyword.iskeyword("True"))# False
Links:
A list of Python built-in objects and functions can be obtained from Python:
print(dir(__builtins__))# Output the listprint(type(__builtins__.list))# = <type 'type'>print(type(__builtins__.open))# = <type 'builtin_function_or_method'>print(listis__builtins__.list)# Trueprint(openis__builtins__.open)# True
Links: