Last active
January 29, 2025 12:44
-
-
Save gustavorv86/f3699e26779214b11f0234050e551561 to your computer and use it in GitHub Desktop.
Difference between Class Attributes and Instance Attributes in 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
#!/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