7-8 如何通过实例方法名字的字符串调用方法

三个接口:

方法一:

>>> help(getattr)
Help on built-in function getattr in module __builtin__:

getattr(...)
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
help(getattr)

输出结果:

方法二:

 

>>> from operator import methodcaller
>>> help(methodcaller)
Help on class methodcaller in module operator:

class methodcaller(__builtin__.object)
 |  methodcaller(name, ...) --> methodcaller object
 |  
 |  Return a callable object that calls the given method on its operand.
 |  After f = methodcaller('name'), the call f(r) returns r.name().
 |  After g = methodcaller('name', 'date', foo=1), the call g(r) returns
 |  r.name('date', foo=1).
 |  
 |  Methods defined here:
 |  
 |  __call__(...)
 |      x.__call__(...) <==> x(...)
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
help(methodcaller)

例子:

>>> s = 'abc123abc456'
>>> s.find('abc',4)
6
>>> strfindabc4 = methodcaller('find','abc',4)  #methodcaller创建一个对象,methodcaller()第一个参数是要调用的函数方法的名字(字符串),其他参数是那个函数方法的参数。
>>> strfindabc4
<operator.methodcaller object at 0x0285ABC0>
>>> strfindabc4(s)      #再将原对象  作为参数传入
6

 

转载于:https://www.cnblogs.com/smulngy/p/9009238.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值