pyMethod类下定义了八个方法,getattr(pyMethod(),’out%s’%str)()
传入的点子名差别,调用不相同的主意。些处方法名称叫字符串。
前言
正文主要给大家介绍了关于Python用字符串调用函数或措施的有关内容,共享出去供大家参谋学习,上面来二只走访详细的牵线:
先看八个例证:
>>> def foo():
print "foo"
>>> def bar():
print "bar"
>>> func_list = ["foo","bar"]
>>> for func in func_list:
func()
TypeError: 'str' object is not callable
我们意在遍历实施列表中的函数,可是从列表中收获的函数名是字符串,所以会唤醒类型错误,字符串对象是不能调用的。如若大家想要字符串变成可调用的指标呢?或是想经过变量调用模块的习性和类的习性呢?
以下有三种形式能够兑现。
eval()
>>> for func in func_list:
eval(func)()
foo
bar
eval()
平时用来实践八个字符串表明式,并回到表达式的值。在那它将字符串转变来对应的函数。eval()
效能强盛不过相比危殆(eval is evil卡塔尔国,不提议采纳。
locals()和globals()
>>> for func in func_list:
locals()[func]()
foo
bar
>>> for func in func_list:
globals()[func]()
foo
bar
locals() 和 globals()
是python的八个放置函数,通过它们能够一字典的主意访谈一些和全局变量。
getattr()
getattr() 是 python 的内建函数,getattr(object,name) 就相当于object.name,可是此间 name 可认为变量。
返回 foo 模块的 bar 方法
>>> import foo
>>> getattr(foo, 'bar')()
归来 Foo 类的习性
>>> class Foo:
def do_foo(self):
...
def do_bar(self):
...
>>> f = getattr(foo_instance, 'do_' + opname)
>>> f()
总结
上述就是那篇小说的全体内容了,希望本文的内容对大家的读书或许办事能带给一定的佑助,假若不通常咱们可以留言沟通,多谢大家对帮客之家的支撑。
参考
Calling a function of a module from a string with the function’s name in
Python
How do I use strings to call functions/methods?
前言
本文首要给大家介绍了有关Python用字符串调用函数或方法的相干内容,分享…
# 1.创建主程序index.py
# 2.创建功能模块
# 3.截取url,获取里面的地址参数执行不同的方法
# url = input("请输入url:")
url = 'www.yuhhcompany.com/account/login'
regex = 'www.yuhhcompany.com'
ret = re.match(regex, url)
if ret != None:
# 匹配成功
host, module, method = url.split('/')
mod = __import__(module, fromlist=True)
if hasattr(mod, method):
ret = getattr(mod, method)()
编制程序语言:
Python面向对象:
class Cat:
def fun1(self):
pass
def fun2(self):
pass
cat1 = Cat()
cat1.fun1()
cat1.fun2()
情势的参数self:
class Cat:
def fun1(self):
print(self)
cat1 = Cat()
print(cat1) # <__main__.Cat object at 0x10073fc50>
cat1.fun1() # <__main__.Cat object at 0x10073fc50>
通常用来执行一个字符串表达式,面向对象。封装:
class Cat:
def fun1(self, name, age):
print(name, age)
def fun2(self, name, age):
print(name, age)
def fun3(self, name, age):
print(name, age)
cat1 = Cat()
cat1.fun1('yhh', 23)
cat1.fun2('yhh', 23)
cat1.fun3('yhh', 23)
class Cat:
def fun1(self):
print(self.name, self.age)
def fun2(self):
print(self.name, self.age)
def fun3(self):
print(self.name, self.age)
cat1 = Cat()
cat1.name = 'yhh'
cat1.age = 23
cat1.fun1()
cat1.fun2()
cat1.fun3()
装进使用情形:
卷入步骤
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def fun1(self):
print(self.name, self.age)
def fun2(self):
print(self.name, self.age)
def fun3(self):
print(self.name, self.age)
对象系列化
import pickle
# 存档
with open('object.pickle', mode='wb') as file:
pickle.dump(cat1,file)
# 读档
with open('object.pickle', mode='rb') as file:
cat1 = pickle.load(file)
cat1.fun1() # YHH 23
继承
class Father:
def fun1(self):
print('Father')
class Son(Father):
def fun2(self):
print('Son')
son = Son()
son.fun1() # Father
son.fun2() # Son
多继承
多世襲面试题:
在pytho3.5中:
# 如果继承关系
class E(C,D):
pass
# A --> C --> E
# B --> D --> E
# E继承CD,C继承A,D即成B
# 则调用的顺序为:E --> C --> A --> D --> B(顶层没有同一个基类)
# 如果A和B同时又继承BASE基类,则调用顺序为:
E --> C --> A --> D --> B --> BASE(顶层有同一个基类)
python2.7不一样
多态
lass Cat():
def fun1(self):
print('fun1')
class Dog():
def fun1(self):
print('fun1')
def function(animal):
animal.fun1()
function(Cat())
function(Dog())
接口
一齐前行,与君共勉,
# 1.创建index.py主程序
# 2.创建commoms模块提供函数
# 3.引入commons模块调用模块中的函数
# commoms.py
def f1():
print('F1')
return 'F1'
# index.py
import commons
if __name__ == '__main__':
ret = commons.f1()
print(ret) # F1
# index.py
if __name__ == '__main__':
module = input('请输入模块名:')
mod = __import__(module)
# ret = mod.f1() # 正常调用
# print(ret) # 正常输出
attr = input('请输入方法名:')
meth = getattr(mod,attr)
ret = meth()
print(ret)
地点的函数也便是调用了2个函数
骨子里getattr()函数才叫反射,通过字符串的格局在模块中寻觅对应的因素,倘若成分海市蜃楼,则报错.
能够由此给getattr(module,arrtib,def)设置暗许值,幸免报错
反射函数
python中,一切皆对象,通过反射,依据字符串去对象中(模块,类)获取成分
扩展
那样的话,出主意是否用场比比较多,作者能够把措施名配置到文件中,读取时接纳getattr动态去调用。
Linux and
python学习沟通3群新开,招待出席,一齐学习.qq 3群:563227894
原型:getattr(对象,方法名)
getattr(pyMethod(),'out%s'%str)() 注意pyMethod()和最后的() 这里之所以这么写pyMethod()加括号是实例化类对象,最后的括号,因为getattr函数反射后,是一个方法对象。
Linux and
python学习交流1,2群已满.
getattr()那么些方法最重要的成效是兑现行反革命射机制。也正是说能够透过字符串获取方式实例。 传入不一样的字符串,调用的法子不风度翩翩致。
C:Python27python.exe D:/weixin/python_getattr.py
this is number
this is string
this is date
Process finished with exit code 0
举个栗子:
不前行,不倒退,结束的景色是未曾的.
#coding=utf-8
class pyMethod(object):
def outstr(self):
print('this is string')
def outint(self):
print('this is number')
def outdate(self):
print('this is date')
if __name__=="__main__":
str = 'int'
getattr(pyMethod(),'out%s'%str)()
str = 'str'
getattr(pyMethod(),'out%s'%str)()
str = 'date'
getattr(pyMethod(),'out%s'%str)()
运作结果: