【问题标题】:Script that works in Jupiter Notebook does not work as expected in IDE在 Jupyter Notebook 中工作的脚本在 IDE 中无法按预期工作
【发布时间】:2019-02-07 08:20:32
【问题描述】:

我已经在 J​​upiter Notebook 中完成了一个熟悉的初学者 Python 项目(银行账户、流动余额——你们都会立即认出),并且运行良好。在 Jupiter Notebooks 中,余额会在存款和/或取款时更新。我想用代码制作一个带有 GUI 的应用程序,但它在我的 IDE (IDLE) 中不起作用。

我已将代码复制到 IDLE 中,如下所示:

class Account():
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def __str__(self):
        return("Account holder: {}\nBalance R".format (self.owner, self.balance))

    def deposit(self, dep_amt):
        self.balance = self.balance + dep_amt


    def withdraw(self, with_amt ):
        if self.balance >= with_amt:
            self.balance = self.balance - with_amt
        else:
            print("insufficient funds")

cust1 = Account("Hernandez, Jose", 100.00)


print("\n", cust1)


cust1.deposit(100.00)
# cust1.withdraw(300.00)


print("\nAccount Holder: ", cust1.owner)
print("Account Balance: R", float(cust1.balance))

本来以为如果连续运行脚本,每次都会触发“cust1.deposit(100)”,余额增加100,就像我反复运行cust1.deposit(100)一样在木星笔记本中。但这不会发生。余额保持不变,为 200(初始余额 100 加上 100 存款)。

我做错了什么?

安德烈

【问题讨论】:

  • 程序退出后,所有创建的对象都被删除。如果您想在多个会话期间保留帐户的状态,则必须将其保存在此代码之外,例如到数据库或文件,以保持简单。或者,为了您的学习目的,只需将cust1.deposit 放入循环中
  • 在 Jupyter 中,内核一直在运行(除非它崩溃或你杀死它),所以任何变量都会持续存在。您甚至可以在底部单元格中初始化一个变量,然后在页面更上方的单元格中使用它(从而在您下次按打开顺序运行它时搞砸您的工作簿)。听起来您的 IDE 运行程序然后关闭内核。

标签: python jupyter-notebook


【解决方案1】:

在 Jupyter 笔记本中,您将在一个单元格上声明 class Account,并在另一个单元格上使用 cust1.deposit(100)。在 Jupyter notebook 中,您可以单独执行一部分代码,这允许您多次运行cust1.deposit(100),因此每次都会增加余额。但在 IDE 中,您不能多次执行部分代码。当你运行它时,整个代码都会被执行,这意味着 balance 被初始化为 100,当调用 cust1.deposit(100) 时它会增加 100。因此,无论您运行多少次,您都会看到 200 的余额。

【讨论】:

    【解决方案2】:

    您的代码按预期工作。问题是,当您直接从 IDE 运行 python 脚本时,它只运行一次,但 Jupyter Notebook 的工作方式不同。当您在 Jupyter 中运行代码行时,该操作的结果会以我只能描述为“python 会话”的方式记住。余额为 300 的原因是因为您可能使用 cust1.deposit(100.00) 运行了两次单元格。如果您想在脚本中执行此操作,您应该执行两次相同的命令:

    cust1 = Account("Hernandez, Jose", 100.00)
    cust1.deposit(100.00)
    cust1.deposit(100.00)
    print("\n", cust1)
    # will print balance with value of 300.00
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2021-12-20
      • 2013-09-30
      • 2021-11-08
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多