python 通过字符串调用对象属性或方法的实例讲解

yipeiwu_com6年前Python基础

有时候需要将属性或方法作为参数传入,这个时候可以通过以下几种方式用字符串调用对象属性或方法

1、eval

In [634]: def getmethod(x,char='just for test'):
  ...:  return eval('str.%s' % x)(char)
  ...: 
In [635]: getmethod('upper')
Out[635]: 'JUST FOR TEST'

2、getattr

In [650]: def getmethod2(x, char='just for test'):
  ...:  return getattr(char, x)()
  ...: 
In [651]: getmethod2('upper')
Out[651]: 'JUST FOR TEST'

3、利用内置库operator

In [648]: def getmethod3(x, char='just for test'):
  ...:  return operator.methodcaller(x, char)(str)
  ...: 
In [649]: getmethod3('upper')
Out[649]: 'JUST FOR TEST'

以上这篇python 通过字符串调用对象属性或方法的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

MAC中PyCharm设置python3解释器

MAC中PyCharm设置python3解释器

MAC上的PyCharm中默认的python解释器是python2的,windows下的没用过不是很清楚,所以特来记录下设置python3解释器的过程。 python3的查找与安装 如果...

python 图片二值化处理(处理后为纯黑白的图片)

python 图片二值化处理(处理后为纯黑白的图片)

先随便招一张图片test.jpg做案例 然后对图片进行处理 # 图片二值化 from PIL import Image img = Image.open('test.jpg')...

使用python3+xlrd解析Excel的实例

实例如下所示: # -*- coding: utf-8 -*- import xlrd def open_excel(file = 'file.xls'):#打开要解析的Excel文...

pygame实现简易飞机大战

利用pygame实现了简易版飞机大战。源代码如下: # -*- coding:utf-8 -*- import pygame import sys from pygame.local...

python绘制多个子图的实例

python绘制多个子图的实例

绘制八个子图 import matplotlib.pyplot as plt fig = plt.figure() shape=['.','o','v','>','<...