I'm trying to create a CRM in Python as a final project to a course.
And I create a dictionary to use like a "database" form my CRM.
First, I tryed update the dict outside a class:
index_db = {} index_db[len(index_db)] = {'name_first': 'Johnny', 'name_last': 'Quest', 'email': '[email protected]', 'phone': '1 365 999999999'} index_db[len(index_db)] = {'name_first': 'Scooby', 'name_last': 'Doo', 'email': '[email protected]', 'phone': '1 365 888888888'} index_db[len(index_db)] = {'name_first': 'Homer', 'name_last': 'Simpson', 'email': '[email protected]', 'phone': '1 365 777777777'} And it's return:
{ 0: { 'name_first': 'Johnny', 'name_last': 'Quest', 'email': '[email protected]', 'phone': '1 365 999999999' }, 1: { 'name_first': 'Scooby', 'name_last': 'Doo', 'email': '[email protected]', 'phone': '1 365 888888888' }, 2: { 'name_first': 'Homer', 'name_last': 'Simpson', 'email': '[email protected]', 'phone': '1 365 777777777' } } It's look great, so I created a class:
class Consumer(object): index_db = {} args = {'name_first': None, 'name_last': None, 'email': None, 'phone': None} def __set__(self, var, val): self.args[var] = val def __insert__(self): self.index_db[len(self.index_db)] = self.args And insert three consumers:
consumer = Consumer() consumer.__set__('name_first', 'Johnny') consumer.__set__('name_last', 'Bravo') consumer.__set__('email', '[email protected]') consumer.__set__('phone', '1 353 30316541') consumer.__insert__() consumer.__set__('name_first', 'Dexter') consumer.__set__('name_last', 'Scientist') consumer.__set__('email', '[email protected]') consumer.__set__('phone', '1 353 33256001') consumer.__insert__() consumer.__set__('name_first', 'Barney') consumer.__set__('name_last', 'Gumble') consumer.__set__('email', '[email protected]') consumer.__set__('phone', '1 353 555961533') consumer.__insert__() And it's return:
{ 0: { 'email': '[email protected]', 'name_first': 'Barney', 'name_last': 'Gumble', 'phone': '1 353 555961533'}, 1: { 'email': '[email protected]', 'name_first': 'Barney', 'name_last': 'Gumble', 'phone': '1 353 555961533'}, 2: { 'email': '[email protected]', 'name_first': 'Barney', 'name_last': 'Gumble', 'phone': '1 353 555961533' } } Oh God, why does not this work?
args, which you create once as a class member.Consumerobjects share a single dictionary, whenever you change one of them, you change all of them. Define an__init__method. that sets up instance variables instead.