class User():
#This variable is stored at the class level, which means that all instances have access to the same value.
user_dict = {}
#This variable is also open at the class level, and is static,
#So all instances will return the same value
@staticmethod
def valid_users_dict():
return_dict = {}
for _, user in User.user_dict.items():
if user.is_valid():
return_dict[user.name] = user
return return_dict
#This method is at the instance level, so it will be different for each instance of the class.
def __init__(self, p_name, p_is_valid_attribute):
self.name = p_name if p_name else ''
self.is_valid_attribute = True if p_is_valid_attribute == 'VALID' else False
User.user_dict[self.name] = self
def is_valid(self):
return self.is_valid_attribute
'''USAGE'''
def main():
#Create 3 class instances. Each time this calls the __init__ method
myUser1 = User('Urtehnoes', 'INVALIDO!!!!')
myUser2 = User('Urtenhoes', 'VALID')
myUser3 = User('RandomName', 'VALID')
#Now, access the variable at the CLASS level, and store it in the var myDict
myDict = User.user_dict #<- Accessed via the Class
instanceDict = myUser1.user_dict #<- Accessed via the class Instance
instanceDict2 = myUser3.user_dict #<- Accessed by a seperate class instance
#Printing it, shows all class instances that were stored during the __init__ procedure at the instance level.
print(myDict)
print(instanceDict)
print(instanceDict2)
#Now we can call the class level method valid_users_dict,
#which will run through the User.user_dict variable, and return only those instances with a valid attribute.
validDict = User2.valid_users_dict()
print(validDict)
if __name__ == '__main__':
main()