I could not figure out why this is happening, the original code (simplified version for clarity): First class:

class Transaction: def __init__(self, amount, date, currency="USD", usd_conversion_rate=1, description=None): self.amount = amount self.date = date self.description = description self.currency = currency self.usd_conversion_rate = us_conversion_rate 

And the second class, in which instances of the first are created:

 class Account(object): def __init__(self,check_number,check_name): self.check_number = check_number self.check_name = check_name self.transactions = [] def apply(self, *args,**kwargs): new_transaction = Transaction(args,kwargs) self.transactions.append(new_transaction) def all_usd(self): print([x.currency for x in self.transactions if x.currency=='USD']) 

Now run:

 >>>a = Account(10,'jiff') >>>a.apply(100,"2008-12-09","RUB") >>>a.apply(10,"2008-12-09","EUR") >>>a.apply(50,'234234','USD') >>>print(a.all_usd()) ['USD', 'USD', 'USD'] True 

As you can see, although three different currencies were set, in spite of this, all three instances of the class were created with currency == 'USD'.

However, if you change the apply function like this:

 def apply(self, amount, date, currency="USD", usd_conversion_rate=1, description=None): new_transaction = Transaction(amount, date, currency, usd_conversion_rate, description) self.transactions.append(new_transaction) 

Then everything is displayed correctly (only one instance of the Transaction class has the value currency == "USD":

 >>>a = Account(10,'jiff') >>>a.apply(100,"2008-12-09","RUB") >>>a.apply(10,"2008-12-09","EUR") >>>a.apply(50,'234234','USD') >>>print(a.all_usd()) ['USD'] False 

I do not understand why this happened (which is wrong in the original function of apply), please explain.

    1 answer 1

    You pass kwargs as a regular parameter instead of using it to complete the parameters:

     new_transaction = Transaction(args,kwargs) -> new_transaction = Transaction(*args, **kwargs) 

    In fact, it turns out that you set the amount and date, and the remaining values ​​are taken by default.

    • Thanks, I figured it out, but I correctly understood that my code turned out that in Transaction (args, kwargs) args and kwargs were not associated with a python with * args and ** kwargs and played the role of just two arguments? - Vova
    • @Vova yes, that's it - etki
    • I would a.apply(10, "2008-12-09", currency="RUB") that you need to call: a.apply(10, "2008-12-09", currency="RUB") , otherwise "RUB" will fall into args, not kwargs. - andy.37