Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>This problem might be related to this question: Python: How do I pass a variable by reference?</p> </blockquote> <p>It is.</p> <blockquote> <p>How can I work around this issue?</p> </blockquote> <p>You need to pass a value that can be modified, and modify it. Numbers cannot be modified: <code>a</code> can be changed from referring to <code>23</code> to referring to <code>42</code> instead, but you cannot cause <code>23</code> to become <code>42</code> or vice-versa.</p> <p>In your case, the natural way to do this is to also notice the other silly thing you're doing - using a bunch of related, similarly-named variables in parallel - and fix that as well, by replacing them with a sequence. The <code>list</code> type is a modifiable sequence. You need to pass the list itself instead of just a numeric quantity, and indicate which element of the list to replace. Except you don't actually need to pass the list, because it's <strong>already a part of <code>self</code></strong>.</p> <pre><code>class Portfolio(object): def __init__(self): self.quantity = [50, 0, 0] self.cash = 0 def __str__(self): return ("%d %d %d %.2f")%(self.quantity[0], self.quantity[1], self.quantity[2], self.cash) def buy(self, stockToBuy, amountToBuy, price, commission=20): self.quantity[stockToBuy] += amountToBuy cost = price * amountToBuy self.cash -= cost + commission </code></pre> <p>For a more flexible solution, you might consider the idea of having an association between stock names and quantities of stock - after all, who knows what stocks the client might want in the future. We can do this simply by using a <code>dict</code> instead.</p> <p>(A constant 'commission' cost is also unrealistic; a percentage makes more sense.)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload