I am trying to dynamically create methods in a class but I'm running into TypeErrors
. I suspect that the issue is that I have not bound the method to the class meaning I cannot call it. However, my efforts with types.MethodType
have failed. Here's an abstract example:
class cls:
def __init__(self):
pass
def method_adder(self):
"""
I want to add a method to this class from
a string
:return:
"""
string_func = "@staticmethod\n"
string_func += "def dynamic_method():"
string_func += " return 'I am a dynamically created string to be a new method'"
exec(string_func, self.__dict__)
c = cls()
print(c)
Outputs:
<__main__.cls object at 0x7fae0aa08e10>
Then
c.method_adder()
meth = c.dynamic_method
print(meth)
produces:
<staticmethod object at 0x7f02375ce748>
but actually using the method:
print(meth())
raises
TypeError: 'staticmethod' object is not callable
I've switched to a 3.7 env as suggested in the comments. I still get the same error but when I remove the @staticmethod
decorator the code works as intended. I could probably work with this, but out of curiosity, any idea how to get the code working with a static method?
I was able to get the following to work -- by moving 'setattr' into the exec statement.
class mycls:
def method_adder(self):
exec("""
@staticmethod
def f():
print ('I am a dynamically created string to be a new method')
setattr(mycls, 'df', f)
""")
c = mycls()
c.method_adder()
mycls.df()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments