?print-pdf
' 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 attributes, as well as these, inherited from the built-in object class and its bases
class type(object)
class type(name, bases, dict)
type(object)
:
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)
:
Employee = type('Employee', (object,), dict())
pesho = Employee()
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)
class Person:
def __init__(self, name):
self.name = name
maria = Person("Maria")
if hasattr(maria, "age"):
print(maria.age)
else:
print("Attribute 'age' not found")
# Output: Attribute 'age' not found
getattr(object, name[, default])
class Person:
def __init__(self, name):
self.name = name
maria = Person("Maria")
age = getattr(maria, "age", "Not specified")
print(age)
# Output: Not specified
setattr(object, name, value)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
maria = Person("Maria Popova", 25)
attr_name = "surname"
setattr(maria, attr_name, "Popova")
print(getattr(maria, "surname"))
# Popova
class Animal:
pass
class Dog(Animal):
pass
d = Dog()
if isinstance(d, Dog):
print("d is a Dog") # Output: d is a Dog
if isinstance(d, Animal):
print("d is also an Animal") # Output: d is also an Animal
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal)) # True
print(issubclass(Dog, object)) # True (all classes inherit from object)
print(issubclass(Animal, Dog)) # False
inspect
built-in moduleinspect
built-in module
import inspect
def foo():
func_name = inspect.stack()[0][3]
caller_name = inspect.stack()[1][3]
print(f"I'm {func_name}.\n{caller_name} called me!")
def bar(f):
f()
bar(foo)
# I'm foo.
# bar called me!
These slides are based on
customised version of
framework