Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class with all possible methods defined/catched

Tags:

python

class

I was trying to put together a stringIO-like function, and I was wondering if it was possible to build a class that catches all possible methods, so that the following would work:

a = magicclass("Hello World!") #Hello world would be the return
print a() #Would print Hello world
print a.read() #should also print hello world
print a.adsf.asdf.xyz.random() #should also print hello world

I have no real idea how to go by this, I could define all the possible methods I want to call, but that'd be problematic if I want to pass this to a black box function.

#This works, but only for the main method.
#Every submethod has to have its own class defined, if you know what I mean.
def emptyreturnfunc(returnval): lambda: returnval
b = emptyreturnfunc("Hello World")
print b() #Does work
print b.asdf() #Doesn't work.

I know why this is, of course, but how can I try to make it work? Any hints?

like image 357
Synthetica Avatar asked Jul 14 '26 05:07

Synthetica


1 Answers

class A(object):
    def __init__(self, msg):
        self.msg = msg

    def __call__(self):
        print self.msg

    def __getattr__(self, name):
        return self


a = A('Hello World')
a()
a.b()
a.b.c()
like image 111
PasteBT Avatar answered Jul 15 '26 19:07

PasteBT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!