* python构造函数中的参数

时间:2018-08-28 10:48:19

标签: python python-3.x

我正在尝试编写一个接受* args的类,因此我需要在 init 中传递* args的示例。我不知道有多少参数将传递给* args,所以不确定如何分配它们。

class bank():

    def __init__(self, *args ):
        if args is not None:
            for i in in argv:
                self.name=i
                #now if there are more argument how do i assign them???like i am using "account" and "name" in below function ("withdraw") 
                #but i dont want to pass this in "balance", i want pass just "name"


    def balance(self,name):
        bal="select account from banktab where name = '%s'" %(self.name)
 #       result=b.query(bal)
        print (bal)

    def withdraw(self,name,account):
        wit="select account from banktab where name = '%s'" %(self.name)
        print (self.name)
        print (self.account)

1 个答案:

答案 0 :(得分:1)

假设您知道args的位置,则可以将它们一个一分配。不过,这是一种不好的做法,因为您不能确保每次参数的索引都相同。

class BankAccount():

    def __init__(self, *args ):
        if args is not None:
            if len(args) == 2:
                self.name = args[0]
                self.balance = args[1]
            elif len(args) == 1:
                self.name = args[0]
                self.balance = 0


bank_account = BankAccount('Jack')

相反,您可以使用kwarg使其更安全。

class BankAccount():

    def __init__(self, **kwargs ):
        if kwargs is not None:
            if 'name' in kwargs:
                self.name = kwargs['name']
            else:
               raise ValueException('Name cannot be empty') 

            if 'balance' in kwargs:
                self.balance = kwargs['balance']
            else:
                self.balance = 0


bank_account = BankAccount(name = 'Jack', balance = 0)

您不能拥有您不知道其名称的变量。在这种情况下,您应该在班级中保留字典并进行相应处理。