-3

I am trying to write a class which accepts *args and so i need example of passing *args in init. i dont know how many parameters will be passed to *args and so not sure how will assign them.

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)
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
  • read args as argv in for loop – Mangesh Gorwadkar Aug 28 '18 at 10:50
  • You can edit your post https://stackoverflow.com/posts/52056034/edit `for i in in argv` is a `SyntaxError` (two `in`) – FHTMitchell Aug 28 '18 at 10:51
  • Assuming that you have read [this](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) during your research - what is your question, exactly? – timgeb Aug 28 '18 at 10:52
  • Also related: [variable variables](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – timgeb Aug 28 '18 at 10:53

1 Answers1

1

Assuming you know the positions of the args you can assign them one by one. This is a bad practice though, as you cannot assure the index of the arguments will be the same each time.

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')

Instead, you can use kwargs and make it safer.

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)

You cannot have variables that you don't know the names of. In that case you should keep a dictionary in your class and handle accordingly.

sertsedat
  • 3,490
  • 1
  • 25
  • 45