zoukankan      html  css  js  c++  java
  • python 通过 实例方法 名字的字符串调用方法

    方式1 - 反射 

    hasattr 方法

    判断当前实例中是否有着字符串能映射到的属性或者方法, 一般会在  getattr 之前作为判断防止报错

    getattr 方法

    获取到当前实例中传入字符串映射到的属性或者方法

    示例

    class A(object):
        def run(self):
            return "run"
    
    
    a = A()
    
    print hasattr(a, "run")         # True
    print getattr(a, "run")         # <bound method A.run of <__main__.A object at 0x0000000002A57160>>
    print getattr(a, "run")()       # run

    方式2 - operator 模块

    methodcaller 方法

    参数

    传入两个参数, 分别为字符串表示映射的方法, 另一个参数为此方法的运行参数,

    返回值

    返回一个 字符串映射到的方法实例

    示例

    import operator
    
    
    class A(object):
        def run(self):
            return "run"
    
        def eat(self, s):
            return s + ": eat"
    
    
    a = A()
    
    print operator.methodcaller("run")  # <operator.methodcaller object at 0x0000000002ADAC08>
    print operator.methodcaller("run")(a)   # run
    print operator.methodcaller("eat", "yangtuo")(a)    # yangtuo: eat
  • 相关阅读:
    旅行计划
    两只塔姆沃斯牛
    迷宫
    异或序列
    异或之和
    素数个数
    SAC E#1
    [JSOI2010]Group 部落划分 Group
    [USACO12FEB]附近的牛Nearby Cows
    [HNOI2008]Cards
  • 原文地址:https://www.cnblogs.com/shijieli/p/11137097.html
Copyright © 2011-2022 走看看