首页 > 编程问答 >{Python} 有没有办法从函数中“提取”返回值变量并在其他地方使用它,而不调用原始函数?

{Python} 有没有办法从函数中“提取”返回值变量并在其他地方使用它,而不调用原始函数?

时间:2024-08-02 15:20:57浏览次数:6  
标签:python function variables

第一次在这里发帖。对 python 来说相对较新,我正在开发一个程序,它基本上是一个随机故事生成器,用于学习语言、发展技能并添加到我的投资组合中。

我有一个主文件(最初启动该程序)、一个简介文件(对于介绍部分,获取用户名以及我试图“提取” user_name 变量的位置),一个函数文件,其中包含我可以反复使用的事件的许多函数,例如 time.sleep 和“YOU DIED”,然后是 5 个“故事内容”文件,这些文件由主文件根据 1-5 中随机生成的数字进行调用。

我想做的是从介绍文件中获取 user_name 变量并能够在故事内容文件中使用该变量而不调用介绍函数本身。只需使用 intro 文件中 intro 函数返回的变量即可。

这是我想要使用用户名的部分的输出: 程序输出

这是相应的代码: 代码有问题

def left_hallway_survival_success():
    from intro import intro
    user_name = intro()
    # Successful hidden passage code for hidden passage random event function    
    functions.time_sleep(3, "You break into a sprint and carefully dodge each pendulum and make it to the other side.\n")
    functions.time_sleep(4, "As you approach the door, you step on a pressure plate and all the pendulums slowly stop swinging.\n")
    functions.time_sleep(4, "They lift up into the ceiling, out of sight.\n")
    functions.time_sleep(3, "You wonder how this is possible, but turn around and continue on.\n")
    functions.time_sleep(5, "Before you stands the door. You're unaware of what is on the other side.\n")
    functions.time_sleep(4, "You carefully grasp the handle and open it slowly. The hinged creak as you do this as the door appears to be very old.\n")
    functions.time_sleep(5, "Inside the door is yet another room. Quite smaller than the one you were just in.\n")
    functions.time_sleep(5, "In the center of the room you notice what appears to be a marble rectangle of some sort.\n")
    functions.time_sleep(5, "The room appears to be some sort of crypt, with a casket.\n")
    functions.time_sleep(3, "You open the lid.\n")
    functions.time_sleep(5, "As the lid slowly scraped across the top of it, you feel a cold breeze escape the casket.\n")
    functions.time_sleep(3, "Chills run down your spine.\n")
    functions.time_sleep(4, "You then look around the room and notice a sign above the casket.\n")
    functions.time_sleep(3, "It reads:\n")
    # Make the name of the sign say the user's name somehow
    functions.time_sleep(1, user_name + "\n")
    #print ("User name - " + intro.intro() + " - from intro file function in main")


    functions.time_sleep(3, "1845-1862\n")
    functions.time_sleep(4, "From the looks of the tomb, he seemed to be a wealthy man...\n")

这是介绍文件代码:

def intro():
    import functions
    
    
    functions.time_sleep(2, "")
    functions.time_sleep(3, "Welcome to this awesome program!")
    functions.time_sleep(2, "This program generates a random interactive story!")
    functions.time_sleep(3, "Enjoy and have fun :)")

    
    user_name = input("Please enter your name: ").capitalize()
    print("Hello " + user_name + "!")
    
    #Return user name value from function
    return user_name

我尝试添加

from intro import intro
user_name = intro()

functions.time_sleep(1, "the user's name is: " + user_name)

这导致介绍函数在故事中间被调用。我还尝试将 user_name 变量添加为 left_hallway_survival_success 函数中的参数,并添加

user_name = intro()

在文件顶部,其中导入位于函数之前,但发生了同样的事情,以及“user_name 未定义”错误。| ||我希望这对我想做的事情来说足够有意义。

提前感谢您的帮助。

Thanks in advance for your help.


理解你想做的事情很重要,你希望避免每次需要用户名时都调用 intro 函数,而是只调用一次并存储结果以供以后使用。在编程中,这被称为缓存或记忆。

以下是几种方法可以做到这一点:

1. 使用全局变量:

  • 虽然全局变量通常被认为是不好的做法,但在你的情况下,它可能是一个可行的简单解决方案。

```python # intro.py user_name = ""

def intro(): global user_name ... # 你现有的代码 user_name = input("Please enter your name: ").capitalize() ...

# left_hallway_survival_success.py from intro import intro, user_name

def left_hallway_survival_success(): # 不需要调用 intro() ... functions.time_sleep(1, user_name + "\n") ... ```

在这种情况下,你在 intro.py 中创建一个名为 user_name 的全局变量。 intro 函数修改此全局变量。然后,你可以从其他模块导入和使用此全局变量。

2. 将用户名作为参数传递:

  • 这种方法更加模块化,并避免使用全局变量。

```python # main.py from intro import intro from left_hallway_survival_success import left_hallway_survival_success

name = intro() left_hallway_survival_success(name)

# left_hallway_survival_success.py def left_hallway_survival_success(user_name): ... functions.time_sleep(1, user_name + "\n") ... ```

在这里,你将用户名作为参数传递给 left_hallway_survival_success 函数。这种方法使你的代码更易于理解和维护,因为它清楚地显示了数据如何在函数之间流动。

选择哪种方法?

  • 如果你的项目很小,并且你只想快速解决问题,那么使用全局变量方法可能更容易。
  • 如果你计划编写更复杂的代码,或者如果其他人也将使用你的代码,最好使用将用户名作为参数传递的方法。这将使你的代码更易于维护和更不容易出现错误。

请记住,清楚且结构良好的代码至关重要。选择对你来说最有意义并且最适合你的项目结构的方法。

标签:python,function,variables
From: 78824195

相关文章

  • 为什么我在 Python 中的 Skip-Gram 实现会产生不正确的结果?
    我正在使用Python实现Word2Vec的Skip-Gram模型。然而,正如生成的嵌入及其可视化所示,我的模型似乎无法正常工作。这是嵌入的3D图的示例,它显示单词聚集在一起并重叠,因此很难区分它们:我怀疑问题在于我的实现而不是绘图函数。importnumpyasnpfromnltk.corpusimpor......
  • 基于SpringBoot的智能购房推荐系统-09040(免费领源码)可做计算机毕业设计JAVA、PHP、爬
    Springboot智能购房推荐系统摘 要近年来随着我国经济的高速发展,房地产业也随之蓬勃发展,尤其是最近国家新出台的房改政策。鼓励居民购房,这对房产公司无疑是一个极好的发展势头。尤为重要的是,近几年随着信息技术和电子商务的快速发展,许多企业都开发了自己房产信息软件。智......
  • Python 基础教学 - 开发规范
    Python基础教学-开发规范一、引言在Python编程中,遵循良好的开发规范是编写高质量、可维护代码的关键。本文将为您详细介绍Python开发中的一些重要规范,帮助您养成良好的编程习惯。二、代码布局缩进使用4个空格进行缩进,避免使用制表符。示例:ifTrue:p......
  • Python基础学习笔记(一)
    文章目录一、下载Python二、变量三、数据类型四、运算符五、语句六、容器类型七、函数function八、常用API九、面向对象类的创建:创建对象:实例成员:实例方法:类成员:静态方法:十、三大特征:封装、继承、多态十一、六大原则:Python基础学习笔记(二)一、下载Python官网:https......
  • 随机森林的可解释性分析(含python代码)
    随机森林的可解释性分析1.引言可解释性的重要性2.随机森林的原理2.1基本原理:2.2随机森林的实现3.随机森林的可解释性分析3.1特征重要性3.2特征重要性3.3SHAP值3.4部分依赖图(PDP)3.5交互特征效应3.6变量依赖图4.结论5.参考文献1.引言在机器学习领域,随机森林......
  • 【Python】模块
    1.模块的概念Python中有一种方法可以把定义放在一个文件里面,并在脚本或者解释器的交互实例中使用它们。这样的文件被称作Python的模块。2.自定义模块在Python中,自定义模块有两个作用,一个作用是规范代码,让代码更容易阅读;另一个作用是方便其他程序使用已经编写好的代码,提高开......
  • 计算机毕业设计-基于python的房屋租赁系统【源码+文档+PPT】
    精彩专栏推荐订阅:在下方主页......
  • 基于python高考志愿填报辅助系统【源码+文档+PPT】
    精彩专栏推荐订阅:在下方主页......
  • nb python 语法
    在bytesized32的开源代码里面看到了一个玄学内容。whileTrue:try:stream=call_gpt(stream=True,model=model,messages=messages,**kwargs)pbar=tqdm(stream,unit="token",total=kwargs.get("max_tokens",8*1024),leave=......
  • Python:下载数据集
    打开网站:搜索        ​​​​​​https://www.kaggle.com直接下载即可(要登陆注册哦),下载完成一定要放到桌面哦,因为读取的是当前目录 在网页上打开上一篇文章所讲的HelloWorld,如果没有安装请跳转http://t.csdnimg.cn/NDJpG输入:importpandasaspddf=pd.read......