I have a class:
class A:
def foo(self):
print("A.foo")
I want a method of the class to have an attribute so I can do something like A.foo.b
.
I tried creating a decorator which returns a callable class:
class AttrStorage:
def __init__(self, b, method):
self.b = b
self.method = method
def __call__(self, *args, **kwargs):
return self.method(*args, **kwargs)
def add_attr(b):
def wrapper(method):
return AttrStorage(b, method)
return wrapper
So I could use it like this:
class A:
@add_attr(1)
def foo(self):
print("A.foo")
Fortunately A.foo.b
worked, but when I used the method, it gave an error:
>>> A.foo.b
1
>>> A().foo()
TypeError: foo() missing 1 required positional argument: 'self'
Is this possible in python? If so, how do I do it?