introspection
A program examining objects and classes at run time, for example with hasattr, getattr, type and isinstance.
In more detail
Introspection lets code ask an object about itself while it runs. hasattr(obj, name) checks the object and then its class, while hasattr(Class, name) sees only what the class defines, never attributes created on self in __init__. getattr reads an attribute by name with an optional default, and setattr creates or changes one.
Example
class R:
def __init__(self):
self.battery = 90
print(hasattr(R(), 'battery'), hasattr(R, 'battery')) # True FalseRelated terms
- isinstance() — isinstance(obj, cls) asks whether an object is an instance of a class or any subclass of it; issubclass does the same for two classes.
- __dict__ — The dictionary that holds an object's own attributes, or a class's own attributes.
- __bases__ — A class attribute holding the tuple of the class's direct parent classes.
Taught in
- math, random And platform — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Class Variables, Instance Variables And __dict__ — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Methods And The self Parameter — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Introspection: hasattr, __name__, __module__ And __bases__ — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Inheritance, super() And Polymorphism — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Object-Oriented Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Twelve Traps, Mostly Objects — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep