Skip to content

Instantly share code, notes, and snippets.

@briandeheus
Last active February 14, 2018 10:02
Show Gist options
  • Save briandeheus/f41a15f0a2f19723aab974749bd7cb9b to your computer and use it in GitHub Desktop.
Save briandeheus/f41a15f0a2f19723aab974749bd7cb9b to your computer and use it in GitHub Desktop.
How to properly use attributes in Python
class FaultyFoo (object):
bar = []
class GoodFoo (object):
def __init__(self):
self.bar = []
foo_one = FaultyFoo()
foo_one.bar.append('foo 1')
foo_two = FaultyFoo()
foo_two.bar.append('foo 2')
print "Faulty Foo one =>", foo_one.bar # Prints ['foo 1', 'foo 2']
print "Faulty Foo two =>", foo_two.bar # Prints ['foo 1', 'foo 2']
print "Faulty Foo one bar memory address =>", hex(id(foo_one.bar)) # Prints 0X1234
print "Faulty Foo two bar memory address =>", hex(id(foo_two.bar)) # Prints 0x1234
"""
Notice how in this example self.bar points to the same memory address.
"""
foo_one = GoodFoo()
foo_one.bar.append('foo 1')
foo_two = GoodFoo()
foo_two.bar.append('foo 2')
print "Good Foo one =>", foo_one.bar # Prints ['foo 1']
print "Good Foo two =>", foo_two.bar # Prints ['foo 2']
print "Good Foo one bar memory address =>", hex(id(foo_one.bar)) # Prints 0x1234
print "Good Foo two bar memory address =>", hex(id(foo_two.bar)) # Prints 0x5678
"""
Why?
When we create a class, it's attributes are mutable by every instance of the class.
This is why you have to set the attributes of a class in the __init__ function.
The init function gets called automatically when you instantiate a class.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment