简体   繁体   中英

Add methods to class dynamically when they are called

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?

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM