Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Python Programming/Reflection

From Wikibooks, open books for an open world
<Python Programming
Previous: Context ManagersIndexNext: Metaclasses


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().

Type

[edit |edit source]

The type method enables to find out about the type of an object. The following tests return True:

  • type(3) is int
  • type(3.0) is float
  • type(10**10) is long # Python 2
  • type(1 + 1j) is complex
  • type('Hello') is str
  • type([1, 2]) is list
  • type([1, [2, 'Hello']]) is list
  • type({'city': 'Paris'}) is dict
  • type((1,2)) is tuple
  • type(set()) is set
  • type(frozenset()) is frozenset
  • ----
  • type(3).__name__ == "int"
  • type('Hello').__name__ == "str"
  • ----
  • import types, re, Tkinter # For the following examples
  • type(re) is types.ModuleType
  • type(re.sub) is types.FunctionType
  • type(Tkinter.Frame) is types.ClassType
  • type(Tkinter.Frame).__name__ == "classobj"
  • type(Tkinter.Frame()).__name__ == "instance"
  • type(re.compile('myregex')).__name__ == "SRE_Pattern"
  • type(type(3)) is types.TypeType

The type function disregards class inheritance: "type(3) is object" yields False while "isinstance(3, object)" yields True.

Links:

Isinstance

[edit |edit source]

Determines whether an object is an instance of a type or class.

The following tests return True:

  • isinstance(3, int)
  • isinstance([1, 2], list)
  • isinstance(3, object)
  • isinstance([1, 2], object)
  • import Tkinter; isinstance(Tkinter.Frame(), Tkinter.Frame)
  • import Tkinter; Tkinter.Frame().__class__.__name__ == "Frame"

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:

Issubclass

[edit |edit source]

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

[edit |edit source]

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:

Callable

[edit |edit source]

For an object, determines whether it can be called. A class can be made callable by providing a __call__() method.

Examples:

  • callable(2)
    • Returns False. Ditto for callable("Hello") and callable([1, 2]).
  • callable([1,2].pop)
    • Returns True, as pop without "()" returns a function object.
  • callable([1,2].pop())
    • Returns False, as [1,2].pop() returns 2 rather than a function object.

Links:

Dir

[edit |edit source]

Returns the list of names of attributes of an object, which includes methods. Is somewhat heuristic and possibly incomplete, as per python.org.

Examples:

  • dir(3)
  • dir("Hello")
  • dir([1, 2])
  • import re; dir(re)
    • Lists names of functions and other objects available in the re module for regular expressions.

Links:

Getattr

[edit |edit source]

Returns the value of an attribute of an object, given the attribute name passed as a string.

An example:

  • getattr(3, "imag")

The list of attributes of an object can be obtained using#Dir.

Links:

Keywords

[edit |edit source]

A list of Python keywords can be obtained from Python:

importkeywordpykeywords=keyword.kwlistprint(keyword.iskeyword("if"))# Trueprint(keyword.iskeyword("True"))# False

Links:

Built-ins

[edit |edit source]

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:

External links

[edit |edit source]
Previous: Context ManagersIndexNext: Metaclasses
Retrieved from "https://en.wikibooks.org/w/index.php?title=Python_Programming/Reflection&oldid=4210288"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp