Home > Enterprise >  Add methods to class dynamically when they are called
Add methods to class dynamically when they are called

Time:11-04

I want to make a script that does something like:

class Foo():
   def magic_method(...):
       return called_function

a = Foo()

a.bar()
> bar
a.foo()
> foo

So basically, if the method doesn't exist in Foo(), don't return an error, but accept it and use it as a string to do other stuff.

Is this possible in python?

CodePudding user response:

You can override __getattr__ magic method:

class Foo():
    def __getattr__(self, name):
        return lambda: name

Now:

>>> a = Foo()
>>> a.something()
'something'

You need to return lambda so calling .something() returns the name of the method (and not just .something).

  • Related