python - 使用参数手动调用内置类型函数

标签 python

我想手动调用内置 str 函数(在本例中为随机性)而不使用 eval

funcs = [str.lower, str.upper]
random.choice(self.funcs)("test")

"test".(random.choice(self.funcs))

最佳答案

你可以这样做

>>> funcs = [str.lower, str.upper]
>>> random.choice(funcs)('Foo')

您不必调用字符串的方法,例如 'Foo'.lower(),而是调用 str 类的 方法,并提供您的string 作为调用该方法的 string 的实例。像这样:

>>> str.lower('FOO')
'foo'

关于python - 使用参数手动调用内置类型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58779875/

相关文章:

python - FileNotFoundError : [Errno2]: No Such file or directory:

python - 我的第一个 python 程序 : can you tell me what I'm doing wrong?

Python 查找函数不起作用。我究竟做错了什么?

python - 从 SQL 数据库导入表并按日期过滤行时,将 Pandas 列解析为 Datetime

python - 为什么使用 for 循环将 '\n' 存储为一项?

python - 在 Django 应用程序中 Ping FeedBurner

Python Spyder : unable to connect to remote ipython kernel

python - stdout/stderr 元组或字符串输出

python - 为什么方法没有引用相等性?

python - 迭代 django 中的大集合 - 缓存问题