Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python Custom Attribute Access Code

Practice customizing attribute reads, fallback lookup, assignment, and deletion safely.

Advanced ~9 min read

Challenge 1

Add an attribute-read hook that logs the name and then performs normal lookup.

python Your answer
class User:
    def __getattribute__(self, name):
        print(f"read {name}")
        

user = User()
user.name = "Ada"
print(user.name)

Press Ctrl⌘Enter to check your answer

Challenge 2

Add a fallback that supplies a default port only when the attribute is missing.

python Your answer
class Config:
    def __init__(self):
        self.host = "localhost"

    def __getattr__(self, name):
        

config = Config()
print(config.host)
print(config.port)

Press Ctrl⌘Enter to check your answer

Challenge 3

Reject negative ages and delegate all accepted assignments to normal storage.

python Your answer
class User:
    def __setattr__(self, name, value):
        

user = User()
user.age = 30
print(user.age)

Press Ctrl⌘Enter to check your answer

Challenge 4

Allow deletion of token and reject deletion of any other attribute.

python Your answer
class Session:
    def __init__(self):
        self.token = "abc"

    def __delattr__(self, name):
        

session = Session()
del session.token
print(hasattr(session, "token"))

Press Ctrl⌘Enter to check your answer