繁体   English   中英

如何在python3中跳转到随机函数

[英]How to jump to a random function in python3

我正在制作一个python脚本,回聊只是为了好玩,我希望它每次在我的代码段中都随机选择一个主题进行讨论

def randsub():
     rand = random.randrange(1,3)
     rand.toString()
     randsub = "sub" + rand
     randsub()

但它一直给我这个错误TypeError:无法将'int'对象隐式转换为str

将函数放在列表中,然后使用random.choice()函数为您随机选择一个。 函数只是对象,就像Python中的其他任何值一样:

import random

def sub_hello():
    print('Well, hello there!')

def sub_nice_weather():
    print("Nice weather, isn't it?")

def sub_sports():
    print('What about them Broncos, eh?')

chat_functions = [sub_hello, sub_nice_weather, sub_sports]
randsub = random.choice(chat_functions)
randsub()

您遇到了特定的错误,因为您试图将一个整数与一个字符串连接起来( "sub"是一个字符串, rand一个整数); 您通常会先将整数转换为字符串,或者使用支持为您将其他对象转换为字符串的字符串模板(例如str.format()str % (values,) )。 但是,即使该字符串与您刚定义的函数名称相同,该字符串也不会变成函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM