Created for
In computer science, reflection is the ability of a computer program to examine, introspect, and modify its own structure and behaviour at runtimeReflection in Wikipedia
dir([object])
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
maria = Person("Maria Popova", 25)
print(dir(maria))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']
We see Person object atributes, as well as these, inherited from the built-in object class
class type(object)
class type(name, bases, dict)
type(object)
- example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
maria = Person("Maria Popova", 25)
print(type(maria))
# <class '__main__.Person'>
type(name, bases, dict)
- exampleDynamically create Employee class
Employee = type('Employee', (object,), dict())
pesho = Employee()
print(type(pesho))
# <class '__main__.Employee'>
type(name, bases, dict)
- exampleDynamically create Employee class, a subclass of Person
Employee = type('Employee', (Person,), dict())
pesho = Employee("Pesho", 30)
print(type(pesho))
# <class '__main__.Employee'>
id(object)
print(id(1))
x = 1
print(id(x))
y=x
print(id(y))
#11065920
#11065920
#11065920
hasattr(object, name)
hasattr()
- example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
maria = Person("Maria Popova", 25)
print(hasattr(maria,"name"))
print(hasattr(maria,"surname"))
#True
#False
getattr(object, name[, default])
getattr()
- example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
maria = Person("Maria Popova", 25)
print(getattr(maria, "age"))
# 25
setattr(object, name, value)
setattr()
- example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
maria = Person("Maria Popova", 25)
setattr(maria, "surname", "Popova")
print(getattr(maria, "surname"))
# Popova
inspect
built-in moduleinspect
built-in moduleGet a function name, within a function. Get the name of the object that called the function.
import inspect
def foo():
func_name = inspect.stack()[0][3]
caller_name = inspect.stack()[1][3]
print("I'm {}.\n{} called me!".format(func_name,caller_name))
def bar(f):
f()
bar(foo)
# I'm foo.
# bar called m
These slides are based on
customised version of
framework