Editor

Build a Proxy Object

Advanced · Write the code · from __getattr__ and __setattr__: Dynamic Attribute Access in Python

From the lesson: __getattr__ and __setattr__: Dynamic Attribute Access in Python

Most of the time, Python attributes are straightforward. You set obj.x = 5, and later obj.x gives you 5. But what if you want attributes that don't actually exist - attributes that are computed on the fly, or that trigger side effects when accessed?

Read the lesson

Create a Proxy class that wraps another object and forwards all attribute access to it. The proxy should also count how many times attributes were accessed.

The constructor takes the wrapped object. Add a method get_access_count() that returns the total number of attribute accesses on the wrapped object.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person('Alice', 30)
proxy = Proxy(p)
print(proxy.name)          # Alice
print(proxy.age)           # 30
print(proxy.name)          # Alice
print(proxy.get_access_count())  # 3
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Proxy:
# Your code here
pass
p = Person('Alice', 30)
proxy = Proxy(p)
print(proxy.name)
print(proxy.age)
print(proxy.name)
print(proxy.get_access_count())

More __getattr__ and __setattr__ exercises

All Python exercises · 50 practice problems · Metaprogramming quiz