Reputation: 7072
I was reading this article about functional programming in Python (3).
However I don't understand this example in the text:
class Bus(object):
passengers = set()
def add_passenger(self, person):
self.passengers.add(person)
bus1 = Bus()
bus2 = Bus()
bus1.add_passenger('abe')
bus2.add_passenger('bertha')
bus1.passengers # returns ['abe', 'bertha']
bus2.passengers # also ['abe', 'bertha']
Why would calling add_passenger() on bus1 instance of the class change the passenger set of bus2?
And what would be the correct way to do it when you don't want this behaviour?
Upvotes: 0
Views: 59
Reputation: 44838
Why would calling add_passenger() on bus1 instance of the class change the passenger set of bus2?
Because there is no "passenger set of bus2
" (and no passenger set of bus1
). In this code:
class Bus(object):
passengers = set()
...passengers
is a class variable which is shared among all instances of this class, yet belongs not to these instances, but to the class itself, so when you change self.passengers
, you actually change Bus.passengers
, and since bus1.passengers
and bus2.passengers
refer to Bus.passengers
, bus1.passengers == bus2.passengers
is always true.
If you do not want this behaviour, implement an __init__
method:
class Bus:
def __init__(self):
self.passengers = set()
Upvotes: 5