如何手动调用带参数的内置类型函数?无需eval随机调用str内置函数
Hey there, I totally get what you're going for here—randomly triggering string methods like str.lower or str.upper without relying on the risky eval function. Let's walk through exactly how to pull this off cleanly, using both approaches you mentioned in your example.
Step 1: Prepare your method list
First, you'll want to create a list that holds references to the string methods you want to use. These are just the method objects themselves (no parentheses needed):
import random # 列出你想随机调用的str内置方法 str_methods = [str.lower, str.upper, str.capitalize, str.title]
Step 2: Two ways to call the random method
There are two straightforward ways to execute the randomly selected method, both completely eval-free:
Option 1: Treat the method as a standalone function
Since unbound string methods (like str.lower) act just like regular functions that take the string as their first argument, you can call them directly after picking one:
# 随机选中一个方法 chosen_method = random.choice(str_methods) # 传入目标字符串作为参数 result = chosen_method("Hello Stack Exchange!") print(result) # 可能输出: hello stack exchange!、HELLO STACK EXCHANGE!、Hello stack exchange! 或者 Hello Stack Exchange!
Option 2: Call the method on the string object
If you prefer to use the typical "dot notation" style, you can still make this work. Since each method in your list has a __name__ attribute that matches its string method name, you can use getattr to fetch the bound method from your string object:
my_string = "Hello Stack Exchange!" chosen_method = random.choice(str_methods) # 通过方法名获取绑定到字符串对象的方法,然后调用 result = getattr(my_string, chosen_method.__name__)() print(result)
This achieves the same effect as writing something like my_string.upper()—but with the random selection baked in.
A quick note on methods with extra parameters
If you want to include methods that require additional arguments (like str.replace or str.strip), you just need to pass those extra parameters when calling the method. For example:
# 加入需要参数的方法 str_methods_with_args = [str.lower, str.upper, str.replace] chosen_method = random.choice(str_methods_with_args) if chosen_method is str.replace: # 给replace传入额外参数 result = chosen_method("Hello World!", "World", "Stack Exchange") else: result = chosen_method("Hello World!") print(result)
内容的提问来源于stack exchange,提问作者Bluescream

