Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:将数据传递给类构造函数_Python_Python 3.x - Fatal编程技术网

python:将数据传递给类构造函数

python:将数据传递给类构造函数,python,python-3.x,Python,Python 3.x,我有一个Account类,它有3个数据字段(id、余额、年利率)。如果我只是打印出余额,或者调用一些函数来获取月利息,等等,一切都正常。。。 但是我也需要展示存款和取款的结果,这就是我被困的地方,我猜我必须做这样的事情 ending_balance = account.withdraw(2500) + account.deposit(3000) 但我不确定如何将期末余额传递给账户构建者,以便利率根据新的余额进行调整 class Account: def __init__(self,

我有一个Account类,它有3个数据字段(id、余额、年利率)。如果我只是打印出余额,或者调用一些函数来获取月利息,等等,一切都正常。。。 但是我也需要展示存款和取款的结果,这就是我被困的地方,我猜我必须做这样的事情

ending_balance = account.withdraw(2500) + account.deposit(3000)
但我不确定如何将期末余额传递给账户构建者,以便利率根据新的余额进行调整

class Account:

    def __init__(self, id, balance, annual_interest_rate):
        self.__id = id
        self.__balance = balance
        self.__annual_interest_rate = annual_interest_rate



    def withdraw(self, withdrawal):
        return float(self.get_balance() - withdrawal)

    def deposit(self, deposit):
        return float(self.get_balance() + deposit)


def main():

    account = Account(1122, 20000, 4.5)
    ending_balance = account.withdraw(2500) + account.deposit(3000)


if __name__ == '__main__':
    main()

因此,您的
取款
存款
必须更新实际字段,以强制使用您的
self。设置余额
或直接设置余额。余额=新余额:

def withdraw(self, withdrawal):
    self.set_balance(self.get_balance() - withdrawal)
    return float(self.get_balance() - withdrawal)

def deposit(self, deposit):
    self.set_balance(self.get_balance() + deposit)
    return float(self.get_balance() + deposit)

这是关于主功能中的逻辑

    account = Account(1122, 20000, 4.5)
    ending_balance = account.withdraw(2500) + account.deposit(3000)
上述行不提供期末余额

做这些改变,

def withdraw(self, withdrawal):
    self.__balance = self.get_balance() - withdrawal
    return float(self.__balance)

def deposit(self, deposit):
    self.__balance = self.get_balance() - deposit
    return float(self.__balance)
并称之为

 account.withdraw(2500)
 ending_balance = account.deposit(3000)

将提供正确的期末余额。

在取款和存款方法中更新
self.\u余额,而不是
return
ing值