Reputation: 65
Why variables declared outside init method do not posses additivity property? For example i have the following class:
class Trade:
allTrades = []
netPosition = 0
def __init__(self, qty):
self.quantity = qty
self.allTrades.append(self.quantity)
self.netPosition += self.quantity
allTrades
(empty list) and netPosition
variables are defined outside the init method while quantity variable defined inside.
Next I create 2 objects of my class and print AllTrades and netPosition for either of them:
deal1=Trade('long', 50, 31)
deal2=Trade('long', 16, 39)
print(deal2.allTrades)
print(deal2.netPosition)
And as far as I see allTrades
(list) variable is additive while netPosition
is not:
print(deal2.allTrades)
returns [50, 16].
And print(deal2.netPosition)
returns 16 however I assume that it should return 66
How can I make print(deal2.netPosition)
return 66 instead of 16?
Upvotes: 0
Views: 106
Reputation: 308452
Your __init__
function creates two object variables which are references to the class variables of the same name. So far so good.
When you call self.allTrades.append
you are modifying (or mutating) your allTrades
object, which is shared between all the objects of your class.
When you do self.netPosition +=
you are not modifying netPosition
because numbers are immutable. Instead you're replacing your reference with another one to a different number object. That means you've broken the connection between your object variable and your class variable. No other objects will see those changes.
To get what you expect, you need to put your number inside another mutable object.
netPosition = [0]
self.netPosition = netPosition
self.netPosition[0] += self.quantity
Upvotes: 1