如果使用实例化对象,来为类动态的添加一个 字符串形式的 方法。

import types

class MyClass:
    @staticmethod
    def extends(self_name, method_name, method_str, ):
        '''
        使用实例化对象 动态的为 类添加一个 字符串形式的 方法。
        :param self_name: 调用该方法的对象 的名字
        :param method_name:  要添加的方法的名字
        :param method_str: 这个方法的 具体代码
        '''
        method_str = method_str + '\n%s.%s=types.MethodType(%s, %s)' % (self_name, method_name, method_name, self_name)
        exec(method_str)


a = MyClass()

method_str = '''
def say(self, name):
    print('My name is', name)
'''
a.extends('a', 'say', method_str)

a.say('alex')  # My name is alex

其实就是这样的:

import types

class MyClass:
  @staticmethod
  def extends(self_name, method_name, method_str):
    pass

a = MyClass()

def say(self, name):
    print('My name is', name)


a.say = types.MethodType(say, a)

a.say('alex')  # My name is alex

具体有啥用呢?  基本用不到。 只是适合小部分场景。 比如从网页上抓到了一写代码。 然后我想执行。
不过网页上的 都是一些 js 代码。 想来js 应该也有相同的方法吧。
只是一个思路。 不必较真。

猜你喜欢

转载自www.cnblogs.com/chengege/p/10958288.html