Skip to content

Instantly share code, notes, and snippets.

@htv2012
Created February 20, 2015 15:45
Show Gist options
  • Save htv2012/3774062b23e928dfc569 to your computer and use it in GitHub Desktop.
Save htv2012/3774062b23e928dfc569 to your computer and use it in GitHub Desktop.
Why return a mutable attribute might be dangerous
#!/usr/bin/env python
""" Why return a mutable attribute might be dangerous """
class Car(object):
def __init__(self, owners):
self._owners = owners
def get_owners(self):
""" Return a list of owners. Getter/setters are evil, but that
is the story for another day.
This is dangerous since someone could modify that list
"""
return self._owners
if __name__ == '__main__':
car = Car(['John', 'Cindy'])
print 'This car belongs to', car.get_owners() # John, Cindy
owners = car.get_owners()
owners.append('Hai') # Danger!
print 'This car belongs to', car.get_owners() # John, Cindy, Hai
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment