Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Created April 22, 2020 12:32
Show Gist options
  • Save ZhouYang1993/337152ac4296770a68c0358df9e03f6f to your computer and use it in GitHub Desktop.
Save ZhouYang1993/337152ac4296770a68c0358df9e03f6f to your computer and use it in GitHub Desktop.
Differences between Class Attribute and Instance Attribute of Python
class MyClass(object):
data = []
def __init__(self, value):
self.instance_data = value
my_instance = MyClass(3)
my_instance.data
# []
my_instance.data.append(1)
my_instance.data
# [1]
MyClass.data
# [1]
# MyClass.data was also changed, because list is mutable.
my_instance.data = [1,2,3]
my_instance.data
# [1, 2, 3]
MyClass.data
# [1]
# MyClass.data didn't change at this time.
# Because the list was totally replaced by a new list
# and my_instance.data became its instance attribute.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment