Created
April 22, 2020 10:26
-
-
Save ZhouYang1993/71998eeff44605b489b1009f461ee9a8 to your computer and use it in GitHub Desktop.
Differences between Class Attribute and Instance Attribute of Python
This file contains 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): | |
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