#!/usr/bin/env python # coding: utf-8 # # Reflektion # Reflektion oder Introspektion ist eine Technik, # wo das Programm etwas über sich selbst weiß. # Es kann während des Ausführens Informationen über die Struktur von Datenstrukturen erfahren, # und eventuell diese Strukturen auch dynamisch modifizieren. # ## Informationen über Datenstrukturen # ### Typ # In[18]: type("abc") # ### Instanzen einer Klasse # In[21]: isinstance(u"abc", str) # In[22]: l = [1,2,3] t = (1,2,3) # In[23]: isinstance(l, (list, tuple)) # In[24]: isinstance(t, (list, tuple)) # ### Attribute abfragen # In[25]: x = "abc" hasattr(x, "date") # In[26]: hasattr(x, "__len__") # ### Attribut auswählen # Statt der "." Notation, geht auch: # In[27]: l = [1] l.append(2) getattr(l, "append")(3) l # ### Attribute auflisten # In[28]: x = "abc" # nur solche, die nicht mit "_" beginnen print([a for a in dir(x) if not a.startswith("_")]) # ### Callable # Eine Funktion, Konstruktur, etc. # In[29]: from datetime import datetime callable(datetime) # In[30]: callable(42) # In[31]: def f(x): return 2*x callable(f) # ## inspect # # Die [inspect](https://docs.python.org/2/library/inspect.html) erlaubt, Objekte während der Ausführung genauer zu untersuchen. # In[32]: import inspect # In[33]: def f2(k, l = "hello"): return l * k # ### Code der `f2` Funktion # In[34]: print(inspect.getsource(f2)) # ### Aufrufspezifikationen für die Funktion `f2` # In[35]: inspect.getargspec(f2) # ### Stack # # Während der Ausführung, kann man auch auf den [Stack des Interpreters](https://docs.python.org/2/library/inspect.html#the-interpreter-stack) zugreifen. # In[36]: x = 42 frame = inspect.currentframe() print(inspect.getframeinfo(frame)) print("Lokale Variable x: %s" % frame.f_locals['x'])