I am trying to gain a better understanding of class variables and the @classmethod decorator in python. I've done a lot of googling but I am having difficulty grasping basic OOP concepts. Take the following class:
class Repository:
repositories = []
repository_count = 0
def __init__(self):
self.update_repositories()
Repository.repository_count += 1
@classmethod
def update_repositories(cls):
if not cls.repositories:
print('appending repository')
cls.repositories.append('twenty')
else:
print('list is full')
a = Repository()
b = Repository()
print(Repository.repository_count)
Output:
appending repository
list is full
2
In the
__init__method, why doesself.update_repositories()successfully call theupdate_repositoriesclass method? I thought thatselfin this case refers to the instantiated object, not the class?The code works without using the
@classmethoddecorator. Why?In the
__init__method why do I need to use the keywordRepositoryinRepository.repository_count += 1? Am I doing this correctly or is there a better practice?