why can't I put a dictionary in my class?

I'm not sure if this explains it yet,  but I found this on stackOverflow:

https://stackoverflow.com/questions/7560172/can-i-use-an-object-an-instance-of-a-class-as-a-dictionary-key-in-python

Then I thought, I want to test this out.  Here is what I came up with.  It seems you can't put
(for {key:value}) a value in the dictionary of a class that does not have an ID in the __main__.
It will throw you NameError's, that stuff doesn't exist.  So the values have to be something already created or the class won't accept your values. Apparently this is true of dictionarys across the board.  It won't let you put a variable in the Value place that is not defined. True of the key also.  They can not be variables that do not yet exist.  Python has to have an ID for the item to place it somewhere and use it.

I'm still going to play with it, after I do some memorizing, but here's my SideTrack of the day:



# Create a class that takes attributes and has an ID
class Yeti(object):
def __init__(self, number, name):
self.number = number
self.name = name

def print_ids(self):
print(self.number, self.name)
print(f"printing ID of number {self.number} and name {self.name}")

# Create an instance of that class:
a_checking = Yeti(45, 'abominable')

# what happens if you put an instance into a dictionary of another class?
# does the __main__ ID of that instance change?
class TryDict(object):

def __init__(self, test_classes):
self.test_classes = test_classes

def dict_id(self):
for key in test_classes:
val = test_classes.get(key)
new = val.print_ids()
print(f"for in tryDict is running {key}: returning new.")
print(f" this is new ID: {val}")
#def print_ids_after_dict(self):
#new_ids = TryDict.dict_id(test_classes)
#print(f"new ids = {new_ids}")

class TestYeti(object):
def __init__(self, test_class):
self.test_class = test_class

def print_ids(self):
print(f"id of test_class = {self.test_class}")

#checking = Yeti(45, 'abominable')
#checking.print_ids()
#print(f"id of checking = {checking}")
#testing = TestYeti(checking)
#testing.print_ids()


testing = TestYeti(a_checking)
testing.print_ids()
test_classes = {'a test class' : Yeti(50, 'Ralph'),
'class exists': a_checking,}

TryDict.dict_id(test_classes)
#TryDict.print_ids_after_dict(test_classes)

Comments

Popular posts from this blog

playing with color in powershell python

JavaScript Ascii animation with while loops and console.log

playing with trigonometry sin in pygame