I have trouble resolving a recursion issue, how can I build a class which would behave like this:
o.foo.bar
would print "o.foo.bar"
when called.o.foo.bar(True)
-> "o.foo.bar(True)"
.Code would look like:
>>> o = MyClass()
>>> result = o.foo.bar
"o.foo.bar"
>>> print(result)
1
I've tried some things with __getattr__
but I cannot manage to handle recursion correctly, I cannot get when the end of the nested chain has been reached and then return the result accurately.
That's the closest I got:
class MyClass:
def __init__(self):
self.a = []
def __getattr__(self, name):
self.a.append(name)
print(self.a)
return self
o = MyClass()
result = o.foo.bar
PURPOSE
This is a simplified code to get rid of context complexity. I'm currently trying to wrap the JS API of Photoshop and this could help calling the software functions by writing same API functions in Python. The print
would be replaced by a call to the PS Server and the result
by the actual result of the call.
The major issue here is you cannot call o.foo.bar
, because a function object's attribute are only accessed when :
They're defined as instance attributes (self.bar
)
The method defining the attribute has been called beforehand, bringing it to existence
class MyClass():
def foo(self):
self.bar='bar'#defined as instance attribute
o = MyClass()
print(o.foo())#method call <=> bar definition
print(o.bar)#bar accessed properly
So you cannot truly reach your goal here, because the basic logic of attribute access within a class is not respected when you type in o.foo.bar
.