
Code
Attribute Control
__getattr__ for dynamic attributes
__getattr__(self, name) lets an object invent attributes on demand,
handy for wrapping a dict so you can write cfg.volume instead of
cfg["volume"]. One rule matters: when the attribute really doesn't
exist, raise AttributeError. hasattr() and getattr(obj, name, default) rely on that exact exception.
def __getattr__(self, name):
try:
return self._data[name]
except KeyError:
raise AttributeError(name) from None
__slots__ for fixed attributes
Normally each instance keeps its attributes in a __dict__, so you can
add new ones at any time (typos included!). Declaring __slots__
replaces that dict with fixed storage: instances use less memory, and
assigning an unlisted attribute raises AttributeError.
class Pixel:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
p = Pixel(1, 2)
p.colour = "red" # AttributeError
Assignment
- Fix
Settings.__getattr__so a missing setting raisesAttributeError(with the messageno setting 'name', e.g.no setting 'speed') instead ofKeyError. - Give
Point__slots__so it only ever hasxandy.
- Fix
Settings.__getattr__so a missing setting raisesAttributeError(with the messageno setting 'name', e.g.no setting 'speed') instead ofKeyError. - Give
Point__slots__so it only ever hasxandy.
main.py Python sleeping
Press Run to try your code, then Check to test it.