Skip to content

Instantly share code, notes, and snippets.

@FerdinaKusumah
Last active October 4, 2021 08:30
Show Gist options
  • Save FerdinaKusumah/10deb444068cf701a3aaa73feb0d4823 to your computer and use it in GitHub Desktop.
Save FerdinaKusumah/10deb444068cf701a3aaa73feb0d4823 to your computer and use it in GitHub Desktop.
Class Attributes vs Instance Attributes
class FooBar:
class_attr: str = "foo bar"
def __init__(self, instance_attr: str):
self.instance_attr = instance_attr
if __name__ == "__main__":
foo = FooBar("foo")
bar = FooBar("bar")
# print the instance attribute of the object foo
print(foo.instance_attr)
# print the instance attribute of the object bar
print(bar.instance_attr)
# print the class attribute of the class FooBar as a property of the class itself
print(FooBar.class_attr)
# print the class attribute of the class as a property of the objects foo,bar
print(bar.class_attr)
print(foo.class_attr)
# try to print instance attribute as a class property
print(FooBar.instance_attr)
# AttributeError: type object 'FooBar' has no attribute 'instance_attr'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment