exec to add a function into a class

跟風遠走 提交于 2019-12-01 10:58:54

You have to bind your function to the class instance to turn it into a method. It can be done by wrapping it in types.MethodType:

import types

class what:
    def __init__(self):
        s = 'def yolo(self):\n\tself.extra = "Hello"\n\tprint self.extra'
        exec(s)
        self.yolo = types.MethodType(yolo, self)

what().yolo()

On a side note, why do you even need exec in this case? You can just as well write

import types

class what:
    def __init__(self):
        def yolo(self):
            self.extra = "Hello"
            print self.extra

        self.yolo = types.MethodType(yolo, self)

what().yolo()

Edit: for the sake of completeness, one might prefer a solution through the descriptor protocol:

class what:
    def __init__(self):
        def yolo(self):
            self.extra = "Hello"
            print self.extra

        self.yolo = yolo.__get__(self)

what().yolo()

Another way, seems more elegant to me:

class what:
    pass

ld = {}
exec("""
def yolo(self):
    self.extra = "Hello"
    print(self.extra)
""", None, ld)
# print('locals got: {}'.format(ld))
for name, value in ld.items():
    setattr(what, name, value)

what().yolo()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!