程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python invokes methods using instance method names

編輯:Python

1、 How to call a method through the string of the instance method name ?

         Actual case :

                 In a project , Our code uses three graphics classes from different libraries :Circle,Triangle,Rectangle.

                 They all have an interface to get the graphic area ( Method ), But the interface name is different . We can implement a unified function to obtain the area , Try each method name , Call the interface of the corresponding class .

         Solution :

                 Method 1( Case solving ): Use built-in functions getattr, Get the method object on the instance by name , And then call .

                 Method 2( Non case resolution ): Use standard library operator Under the methodcaller Function call .

2、 Code demonstration

(1) Case code implementation

class Circle(object): # round
def __init__(self, r):
self.r = r
def area(self):
return self.r ** 2 * 3.14
class Triangle(object): # triangle
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def getArea(self):
a, b, c = self.a, self.b, self.c
p = (a + b + c) / 2
area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
return area
class Rectangle(object): # rectangular
def __init__(self, w, h):
self.w = w
self.h = h
def get_area(self):
return self.w * self.h
# 3 The area method names of the figures are different from each other
# It is better to implement a function in the user's code , It can unify the area of a graph
def get_area(shape):
# Iterate over those method names , stay shape Object respectively attempts to get method properties
for name in ('area', 'getArea', 'get_area'):
# Call that method if you can get it , Unable to get continue trying
# parameter list : object , name , The default value is None
f = getattr(shape, name, None)
if f:
# Return to the method of obtaining the drawing area
return f()
shape1 = Circle(2)
shape2 = Triangle(3, 4, 5)
shape3 = Rectangle(6, 4)
shapes = [shape1, shape2, shape3]
# Use map Function to obtain shapes The area of each drawing instance in the list
print(list(map(get_area, shapes)))

(2) Method 2 Example demonstration

from operator import methodcaller
s = 'abc123abc456'
# From 4 Start looking for abc character string
print(s.find('abc', 4))
# Use methodcaller Realization s.find
# The first 1 The first parameter is the method name , Then follow the parameter with the method name , Get an object
# This object can make a call , Get the same result as above .
print(methodcaller('find', 'abc', 4)(s))


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved