I have this code I am trying out and I can't figure out how to modify the instance attributes when I use them as parameters when calling a method.
class Portfolio(object):
def __init__(self):
self.qtyA = 50
self.qtyB = 0
self.qtyC = 0
self.cash = 0
def __str__(self):
return ("%d %d %d %.2f")%(self.qtyA, self.qtyB, self.qtyC, self.cash)
def buy(self, stockQty, qtyToBuy, price, commission=20):
stockQty += qtyToBuy
print stockQty
buyTransaction = price * qtyToBuy
self.cash -= buyTransaction + commission
>>> p = Portfolio()
>>> p.buy(p.qtyA,10,25)
60
>>> print p
50 0 0 -270.00
What seems to be happening is that a new variable stockQty
is being created when buy
is called. I would expect that a reference to the attribute qtyA
would be passed instead of the value. This problem might be related to this question: How do I pass a variable by reference?
How can I work around this issue?