BankAccount客户python

时间:2016-07-27 15:03:48

标签: python class random bank customer

所以今天我有一项任务要求我建立一个银行账户类。为了使我的输出与预期输出相匹配,我拥有一切。

我的输出:

Alin,Smith (SSN:111-11-1111) account number: 5040470401, balance: $20000
Alin,Smith (SSN:111-11-1111) account number: 5040470401, balance: $15000
Alin,Smith (SSN:111-11-1111) account number: 5040470401, balance: $15100.0
Mary,Lee (SSN:222-22-2222) account number: 5040470401, balance: $10000
Mary,Lee (SSN:222-22-2222) Insufficient Funds to withdraw: $15000
Mary,Lee (SSN:222-22-2222) account number: 5040470401, balance: $10000
Mary,Lee (SSN:222-22-2222) account number: 5040470401, balance: $10500.0

然而,正如您所看到的,即使Mary和Alin是不同的客户,他们也会生成相同的帐号。

我今天的问题是如何为我的银行帐户类中创建的每个客户对象提供不同的随机10位数帐号。

现在我有我的客户类

class Customer:
    def __init__(self,firstName, lastName, social):
        self.firstName = firstName 
        self.lastName = lastName 
        self.social = social 

    def setfirstName(self,firstName):
        self.firstName = firstName

    def setlastName(self,lastName):
        self.lastName = lastName

    def __str__(self):
        self.name = "{},{} (SSN:{})".format(self.firstName, self.lastName,self.social)
        return self.name 

然后是我的BankAccount类(仅包含随机数部分):

class BankAccount(Customer):
    from random import randint
    n = 10
    range_start = 10**(n-1)
    range_end = (10**n)-1
    accountNumber = randint(range_start, range_end)

    def __init__(self,customer,balance = 0):
        self.customer = customer
        self.balance = balance 

    def setCustomer(self,customer,accountNumber):
        self.customer = customer
        self.accountNumber = accountNumber 

    def getCustomer(self,customer,accountNumber):
        return self.customer, self.accountNumber

     def __str__(self):
        customer = "{} account number: {}, balance: ${}".format(self.customer,self.accountNumber,self.balance)
        return customer 

我认为对于我制作的每个帐户对象,都会生成一个新的随机数,但似乎并非如此。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您将accountNumber定义为类变量,因此创建类后,将为该类的每个实例分配相同的accountNumber

您应该在实例中创建帐号,而不是作为类变量:

def __init__(self,customer,balance = 0):
    self.customer = customer
    self.balance = balance 
    self.accountNumber = randint(self.range_start, self.range_end)

更重要的是,由于您几乎总能保证使用random模块,因此您可以考虑将import语句移至模块顶部。

另一方面,您应该考虑使用更可靠的逻辑来生成唯一的帐号。 randint会在某个时刻创建重复的帐号,这是您不想要的行为。您可以查看uuid模块。

答案 1 :(得分:1)

这是因为您正在静态设置变量。您的第accountNumber = randint(range_start, range_end)行只会被调用一次。将其移至__init__ BankAccount来电,您应该获得不同的帐号。

答案 2 :(得分:0)

当您创建accountNumber时,它会静态创建一次。如果你重复使用它,它每次都是一样的。

比较类似的输出:

import random

account_number = random.randint(1,10)

for i in range(10):
    print account_number

使用:

for i in range(10):
    account_number = random.randint(1,10)
    print account_number

将它移到课堂内即可。