Created
February 20, 2015 15:45
-
-
Save htv2012/3774062b23e928dfc569 to your computer and use it in GitHub Desktop.
Why return a mutable attribute might be dangerous
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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