It is perfectly explained in the standards here [1] saying that:
<quote>
In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).
</quote>
Therefore, I wrote a code following what the standard says:
<code>
class Sample():
def __init__(self):
self.a = -10
def __getattribute__(self, name):
if name == 'a':
return object.__getattribute__(self, name)
raise AttributeError()
s = Sample()
result = s.a
print(result)
</code>
I did not fall into recursion, and the output was
-10
def __getattribute__(self, name):class Demo:
42d = Demo()
d.answer
Traceback (most recent call last):d.whatever
"What's up?"d.question = "What's up?"
d.question
However, when I try the code without deriving from a class:
class AnyClassNoRelation:
pass
class Sample():
def __init__(self):
self.a = -10
def __getattribute__(self, name):
if name == 'a':
return AnyClassNoRelation.__getattribute__(self, name)
raise AttributeError()
s = Sample()
result = s.a
print(result)
and calling __getattribute__ via any class (in this example class AnyClassNoRelation) instead of object.__getattribute__(self, name) as the standard says call using the base class, I get the same output: no recursion and -10.
So my question:
How come this is possible (having the same output without using the base class's __getattribute__? Although the standards clearly states that __getattribute__ should be called from the base class.
TrueAnyClassNoRelation.__getattribute__ is object.__getattribute__
def __getattribute__(self, name):class NoRelation:
def __getattribute__(self, name):class Demo:
'<SOME_ARG>'Demo().some_arg
<quote>
In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).
</quote>
Literally, I can call __getattribute__ with anyclass (except Sample cause it will be infinite recursion) I define and it works just fine. Could you explain me why that happens?
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 446 |
Nodes: | 16 (2 / 14) |
Uptime: | 19:25:51 |
Calls: | 9,234 |
Calls today: | 1 |
Files: | 13,494 |
Messages: | 6,063,226 |