class Fun:
def __init__(self):
self.converted_list = self.convert_list()
self.map_result = self.map_list()
#avilable for other funs
def convert_list(self):
return list(user_input)
def map_list(self):
global fun_name
return list(map(lambda x: getattr(x, fun_name)(), self.converted_list))
#clarify: map x.fun_name() -> converted_list
def return_bool(self):
for each_bool in self.map_result: #map_result(type) -> list
if each_bool:
return True
else:
pass
return False
if __name__ == '__main__':
user_input = input()
fun=Fun()
if 0 < len(user_input) < 1000:
fun_set = ['isalnum','isalpha','isdigit','islower','isupper']
for fun_name in fun_set: #bool_result(5) in fun_set elements
print(fun.return_bool())
问题:如何在for循环中使用fun_name到Fun类的map_list的fun_name? 我发现nonlocal,global。但我不知道细节。我也尝试编码self.fun_name
为什么要“字符串化”要调用的字符串方法的名称?函数是对象,所以只需创建一个函数/可调用数组:
methods = [str.isdigit, str.islower, str.isupper]
for method in methods:
print(method("hello"))
输出:
False
True
False
此示例之所以有效,是因为实例方法的第一个参数将是对(字符串)实例本身的引用。