Python properties and class introspection
How Python properties give controlled access to attributes, plus a few class introspection helpers (isinstance, issubclass, __bases__, dir).
A Python property lets code run when an attribute is read or assigned, while callers keep the simple obj.attr syntax. The second part shows helpers for inspecting classes and objects at run time. Reference: built-in functions: property.
Property with a getter and a setter
class Person:
"""A person with a name and a city of residence."""
def __init__(self, name):
self.name = name
self._city = "Paris" # leading underscore: internal attribute
def _get_city(self):
print("Reading city")
return self._city
def _set_city(self, new_city):
print(f"{self.name} moves to {new_city}.")
self._city = new_city
city = property(_get_city, _set_city)
Usage:
p = Person("example")
print(p.city) # calls _get_city: prints "Reading city", then "Paris"
p.city = "Lyon" # calls _set_city
Introspection helpers
| Tool | Purpose |
|---|---|
isinstance(obj, cls) |
True if obj is an instance of cls or of a subclass |
issubclass(sub, cls) |
True if sub inherits from cls |
cls.__bases__ |
Tuple of the direct parent classes, in declaration order |
obj.__dict__ |
Dictionary of the instance attributes |
dir(obj) |
Sorted list of attribute and method names |
class A: pass
class B: pass
class C(A, B): pass
C.__bases__ # (A, B)
issubclass(C, A) # True
Notes
- The decorator form is more common:
@propertyon the getter and@city.setteron the setter. It behaves the same way. - The leading underscore in
_cityand in the accessor names is a naming convention meaning "internal"; Python does not enforce it.