gpt4 book ai didi

Python - 将 2 个类导入主文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:48 26 4
gpt4 key购买 nike

我不太确定如何用问题的措辞......

我有 3 个文件:

银行.py:

class Bank(object):

def __init__(self, money):
self.money = money

def currentMoney(self):
print "You currently have $%d" %self.money

def useMoney(self, money_use):
self.money = self.money - money_use
print "You used $%d" %money_use
self.currentMoney()

def getMoney(self, money_get):
self.money = self.money + money_get
print "You received $%d" %money_get
self.currentMoney()

事件.py:

class Event(object):

def Event1(self):
print "Your dad needs money. Will you give him?"
decision = raw_input("Yes or No")
if decision == "Yes":
Bank.useMoney(500)
elif decision == "No":
print "Your father is sad"
else:
print "I do not know what are you talking about"

ma​​in.py:

import bank
import event

Bank = bank.Bank(1000)
Event = event.Event()

Event.Event1()

当我执行代码时。我收到以下错误:

NameError: global name 'Bank' is not defined

基本上,我想做的是使用 event.py 创建一系列会影响金钱的事件,我可以使用 main.py 运行不同的系列事件。

你能告诉我怎么做吗?谢谢!

最佳答案

在另一个答案中提到,您需要在 event.py 中导入 Bank

from bank import Bank

话虽如此,查看 event.py 中的代码,您将在该行遇到另一个错误:

 Bank.useMoney(500)

由于 useMoney()self 作为第一个参数,因此它需要在 Bank 实例 而不是类本身(在 Java 类型中,useMoney 是实例方法,而不是静态方法)。

认为您的意图是将Bank 实例包含在Event 中,然后调用useMoney 每当调用 Event1 时。

关于Python - 将 2 个类导入主文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12585819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com