Python:在函数之间传递用户输入的变量时出错

2024-06-03 07:09:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试从头开始构建一个简单的ATM程序(基于文本)。我的问题是在函数之间传递用户输入的变量。我得到的错误是(init()正好接受3个参数(给定1个参数))。有人能解释一下发生了什么,我做错了什么吗

class Atm:
    acctPass = 0
    acctID = 0

    def __init__(self, acctID, acctPass):
        #self.acctName = acctName
        #self.acctBal = acctBal
        self.acctPass = acctPin
        self.acctID = acctID

    def greetMenu(self, acctID, acctPass):

        while acctPass == 0 or acctID == 0:
            print "Please enter a password and your account number to proceed: "
            acctpass = raw_input("Password: ")
            acctID = raw_input("Account Number: ")
            foo.mainMenu()
            return acctPass, acctID # first step to transfer data between two functions

    def mainMenu(self, acctID, acctPass):
        print ""
        acctpass = foo.preMenu(acctPass, acctID)
        print acctPass
        print "Made it accross!"

    def deposit():
        pass

    def withdrawl():
        pass

foo = Atm()
foo.greetMenu()

Tags: toself参数rawfooinitdefprint
2条回答

这是用foo = ATM()调用的构造函数

def __init__(self, acctID=0, acctPass=0):

=0添加到参数会将它们初始化为0 现在您已经重写了构造函数以接受1、2或3个值

在greetmenu中

def greetMenu(self, acctID, acctPass):

    while acctPass == 0 or acctID == 0:
        print "Please enter a password and your account number to proceed: "
        acctpass = raw_input("Password: ")
        acctID = raw_input("Account Number: ")
        foo.mainMenu()
        return acctPass, acctID # first step to transfer data between two functions

您需要要么将参数发送到函数ATM.greetmenu(1234,'pwd'),要么像这样使用类中定义的参数

def greetMenu(self):

    while self.acctPass == 0 or self.acctID == 0:
        print "Please enter a password and your account number to proceed: "
        self.acctpass = raw_input("Password: ")
        self.acctID = raw_input("Account Number: ")
        foo.mainMenu()

        #return acctPass, acctID # first step to transfer data between two functions
foo = Atm()

只将1个参数传递给Atm.__init__隐式self。其他两个参数(acctIdacctPass)丢失,因此python会抱怨

在我看来,您可以一起摆脱__init__,并绑定greetMenu中的实例属性:

class Atm:
    acctPass = 0
    acctID = 0

    def greetMenu(self):

        while self.acctPass == 0 or self.acctID == 0:
            print "Please enter a password and your account number to proceed: "
            self.acctpass = raw_input("Password: ")
            self.acctID = int(raw_input("Account Number: "))

        self.mainMenu()

# etc.

在这里,您可能仍然需要对mainMenu进行一些处理才能使其正常工作(注意,现在我们不是通过函数调用参数传递参数值存储在上)

相关问题 更多 >