Part 14 / Topic 3 of 11
Attribute access
An attribute is a name after a dot: user.name, user.save(). Most attributes of an object live in a dict called __dict__; methods and class variables live in the class's own __dict__.
Think of a hotel: your room locker (instance __dict__) is checked first, then the hotel reception (the class).
class Account:
bank = "Python Bank" # class attribute
def __init__(self, owner):
self.owner = owner # instance attribute
acc = Account("Asha")
print(acc.__dict__) # {'owner': 'Asha'}
print("bank" in Account.__dict__) # True
print(acc.bank) # Python Bank (found on the class)
getattr, setattr, hasattr
These do obj.name when the name is in a string, for example read from a file or a form.
class Account:
def __init__(self, owner):
self.owner = owner
acc = Account("Asha")
field = "owner"
print(getattr(acc, field)) # Asha (same as acc.owner)
print(getattr(acc, "city", "unknown")) # unknown (default instead of an error)
setattr(acc, "city", "Pune") # same as acc.city = "Pune"
print(hasattr(acc, "city")) # True
print(vars(acc)) # {'owner': 'Asha', 'city': 'Pune'}
__getattr__ vs __getattribute__
__getattr__(self, name)is called only when normal lookup fails. Good for defaults and fallbacks.__getattribute__(self, name)is called for every attribute access. Rarely needed and easy to break (infinite recursion). Avoid it.
class Settings:
DEFAULTS = {"theme": "light", "language": "en"}
def __init__(self, **chosen):
self.__dict__.update(chosen)
def __getattr__(self, name): # only for names not found normally
if name in self.DEFAULTS:
return self.DEFAULTS[name]
raise AttributeError(f"no setting {name!r}")
prefs = Settings(theme="dark")
print(prefs.theme) # dark (found in __dict__, __getattr__ not called)
print(prefs.language) # en (missing, so __getattr__ supplies the default)
print(hasattr(prefs, "font")) # False (AttributeError means "not there")
Always raise AttributeError for unknown names, so hasattr and getattr(..., default) keep working.
Properties recap
You met @property in Part 9: a method that is read like an attribute, often to compute or check a value.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return round(3.14159 * self.radius ** 2, 2)
print(Circle(2).area) # 12.57 (no brackets)
The next topic shows what @property really is.
Full program: examples/03_attributes_and_descriptors.py.
Done here? The practice set for Part 14 — 8 exercises with solutions — is on the part page.