Code Explanation:
1. Defining the Class
class Safe:
A class named Safe is defined.
2. Overriding __getattribute__
def __getattribute__(self, name):
if name == "open":
return super().__getattribute__(name)
return "blocked"
__getattribute__ is called for every attribute access on an instance.
It receives:
self → the instance
name → the name of the attribute being accessed
Logic:
If the attribute name is "open", delegate to Python’s normal lookup using super().__getattribute__.
For any other attribute, return the string "blocked" instead of the real value.
So:
s.open → real method
s.x, s.anything_else → "blocked"
3. Defining the open Method
def open(self):
return "ok"
A normal instance method that returns "ok".
4. Creating an Object
s = Safe()
Creates an instance of Safe.
5. Accessing Attributes
print(s.open(), s.x)
Let’s evaluate each part:
▶ s.open()
s.open triggers __getattribute__(s, "open").
Since name == "open", it calls super().__getattribute__("open").
That returns the actual method open.
() calls it → returns "ok".
▶ s.x
s.x triggers __getattribute__(s, "x").
"x" ≠ "open", so it returns "blocked".
No error is raised.
6. Final Output
ok blocked
Final Answer
✔ Output:
ok blocked


0 Comments:
Post a Comment