python3 50个练习例子之通过实例的方法名字符串,调用方法

  1. getattr()
# getattr(object, name[, default]) -> value

class Rectangle(object):
    def __init__(self,w,h):
        self.w = w
        self.h = h
        
    def area(self):
        return self.w * self.h

r1 = Rectangle(3,4)
f = getattr(r1,'area1')  #AttributeError: 'Rectangle' object has no attribute 'area1'
f = getattr(r1,'area') # 得到的area这个方法名
f() # 等同于 r1.area()  
  1. operator.methodcaller
from operator import methodcaller

s = 'abc1234abc1234'
print(s.find('abc',4)) # 7

# methodcaller(name, ...)
methodcaller('find','abc',4)(s) # 等同于s.find('abc',4)

你可能感兴趣的:(python)