Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Created April 22, 2020 10:26
Show Gist options
  • Save ZhouYang1993/71998eeff44605b489b1009f461ee9a8 to your computer and use it in GitHub Desktop.
Save ZhouYang1993/71998eeff44605b489b1009f461ee9a8 to your computer and use it in GitHub Desktop.
Differences between Class Attribute and Instance Attribute of Python
class MyClass(object):
class_attr = 0
def __init__(self, instance_attr):
self.instance_attr = instance_attr
MyClass.class_attr
# 0
MyClass.instace_attr
# Traceback (most recent call last):
# File "/usr/lib/python3.6/code.py", line 91, in runcode
# exec(code, self.locals)
# File "<input>", line 1, in <module>
# AttributeError: type object 'MyClass' has no attribute 'instace_attr'
my_instance = MyClass(1)
my_instance.instance_attr
# 1
my_instance.class_attr
# 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment