Python动态生成方法

背景:想要通过读取配置文件动态生成方法

实践1

使用关键字exec实现生成方法,参考 https://www.cnblogs.com/wjlv/p/14276827.html

m = """
def fn(a,b):
    c=2
    s=a+b+c
    return s
"""

exec(m)

print(fn(3, 6))

执行结果:

11

实践2

直接给类和方法绑定自定义方法 A.fun=fun

class A():
    dd = 37

    def __init__(self, de):
        self.de = de


print(globals())
m = """
def fn(a,b):
    c=2
    s=a+b+c
    return s
"""

exec(m)
print(globals())

if __name__ == '__main__':
    c = 17
    a = A(35)
    print('\n\n\n')
    print(A.__dict__)
    print(a.__dict__)

执行结果:

可以看到方法的确已经生成了,但是此时无论是类A还是实例a都没有这个方法。下面给这个类加上此方法:


class A():
    dd = 37

    def __init__(self, de):
        self.de = de


m = """
def fn(a,b):
    c=2
    s=a+b+c
    return s
"""

exec(m)

A.fn = fn  # 这里需要注意的是,fn函数会被当做 staticmethod,所以是不能被实例调用的

if __name__ == '__main__':
    c = 17
    a = A(35)
    print(A.__dict__)
    print(A.fn(5, 6))
    print(a.__dict__)
    # print(a.fn(5, 6))  # 报错  TypeError: fn() takes 2 positional arguments but 3 were given   因为实例调用多传了self

执行结果:

优化实践2

使用types给类添加方法,参考 https://blog.csdn.net/qdpython/article/details/107879804

import types


class A():
    dd = 37

    def __init__(self, de):
        self.de = de

    def ss(self, a):
        self.de = self.de + a


m = """
def fn(a,b):
    c=2
    s=b+c
    return s
"""

exec(m)

A.f = types.MethodType(fn, A)  # 这里fn函数会被当做类方法,第一个参数a,会被当作self传入,所以类和实例都能调用此方法

if __name__ == '__main__':
    c = 17
    a = A(35)
    print(A.__dict__)
    print(A.f(6))
    print(a.__dict__)
    print(a.f(3))

执行结果:

可以看到无论是实例还是类,均能够使用自定义的方法

这里补充下,如果只想给实例添加私有自定义方法,可以 a.fun=types.MethodType(fn, a)

import types


class A():
    dd = 37

    def __init__(self, de):
        self.de = de

    def ss(self, a):
        self.de = self.de + a


m = """
def fn(a,b):
    c=2
    s=b+c
    return s
"""

exec(m)

if __name__ == '__main__':
    c = 17
    a = A(35)
    a.f = types.MethodType(fn, a)
    print(A.__dict__)
    # print(A.f(6))  # AttributeError: type object 'A' has no attribute 'f' 实例的私有方法,类无法调用
    print(a.__dict__)
    print(a.f(3))

执行结果: 实例的私有方法,类无法调用

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值