码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-05-08 17:42:08      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:cep   调用   method   hid   color   raise   alt   The   justify   

技术分享图片

三个接口:

技术分享图片

方法一:

技术分享图片
>>> 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 doesnt
    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

 

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

标签:cep   调用   method   hid   color   raise   alt   The   justify   

原文地址:https://www.cnblogs.com/smulngy/p/9009238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!