This was a comment from ee_programmer in reference to one of the Python code snippets.
"""
I was expecting the first class instance to only have one dictionary entry
{'person0': 0} rather than two dictionary entries. Similar expectation with second
class instance.
How do I create and assign value to separate dictionaries for each class instance?
Thanks-
ee_programmer
"""
class Person(object):
def __init__(self, name=None, job=None, quote=None, hash={}):
self.name = name
self.job = job
self.quote = quote
self.hash = hash
#create an empty list
personList = []
#create two class instances
personList.append(Person("Payne N. Diaz", "coach", "Without exception, there is no rule!"))
personList.append(Person("Mia Serts", "bicyclist", "If the world didn't suck, we'd all fall off!"))
# assign a single entry to the dictionary of each class instance
personList[0].hash['person0'] = 0
personList[1].hash['person1'] = 1
# print dictionary of first class instance
print personList[0].hash # {'person0': 0, 'person1': 1}
# print dictionary of second class instance
print personList[1].hash # {'person0': 0, 'person1': 1}
First off, hash is a poor choice for a variable name since it is also a Python function so I changed that to myhash, Secondly, be careful assigning defaults to mutable arguments like lists and dictionaries. This will work with no surprises ...
class Person(object):
def __init__(self, name=None, job=None, quote=None, **myhash):
self.name = name
self.job = job
self.quote = quote
self.myhash = myhash
#create an empty list
personList = []
#create two class instances
personList.append(Person("Payne N. Diaz", "coach", "Without exception, there is no rule!"))
personList.append(Person("Mia Serts", "bicyclist", "If the world didn't suck, we'd all fall off!"))
# test empty myhash
print personList[0].myhash # {}
# assign a single entry to the dictionary of each class instance
personList[0].myhash['person0'] = 0
personList[1].myhash['person1'] = 1
# print dictionary of first class instance
print personList[0].myhash # {'person0': 0}
# print dictionary of second class instance
print personList[1].myhash # {'person1': 1}