Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Created April 16, 2022 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavorv86/f3699e26779214b11f0234050e551561 to your computer and use it in GitHub Desktop.
Save gustavorv86/f3699e26779214b11f0234050e551561 to your computer and use it in GitHub Desktop.
Difference between Class Attributes and Instance Attributes in Python.
#!/usr/bin/env python3
class MyPersonClass:
# Class attributes
count_instances = 0
def __init__(self, name: str, surname: str, years: int):
MyPersonClass.count_instances += 1
# Instance attributes
self.name = name
self.surname = surname
self.years = years
def __str__(self):
return "{}, {} ({})".format(self.surname, self.name, self.years)
def main():
p1 = MyPersonClass("Peter", "Parker", 26)
p2 = MyPersonClass("Bruce", "Banner", 38)
p3 = MyPersonClass("Tony", "Stark", 36)
p4 = MyPersonClass("Steve", "Rogers", 103)
print(p1)
print(p2)
print(p3)
print(p4)
print("Instances of MyPersonClass: {}".format(MyPersonClass.count_instances))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment