Created
April 22, 2020 12:32
-
-
Save ZhouYang1993/337152ac4296770a68c0358df9e03f6f to your computer and use it in GitHub Desktop.
Differences between Class Attribute and Instance Attribute of Python
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
| 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