Python: Creating and using empty objects.

Submitted by john on Mon, 03/20/2017 - 16:48

Python LogoFirst off why would you create an object to store objects? Well, easy retrieval, appropriately named groupings, and well... it is just plain cool. Think of this code:

#!/usr/bin/env python
Cservices = {}
Dservices = {}

Well, they are all services but the first one is C services and the second one is D services. Coders already know how this is going to go bad. Sure you can create a class and store all your stuff by accessing that class, but sometimes you don't need to actually do anything with the stored data. You just need to put it in the right bucket. Created an object in the __main__ class is an easy way to do it. 

>>>services = type("Object_Name", (object,), {})()
>>>services.C = {}
>>>services.D = {}

Isn't that prettier? You don't have to slam dictionaries in there like I did. You can put lists, JSON objects, dictionaries, strings, tuples, integers, floats.. you get the idea. [[OK I will answer the question burning in your brain. The difference between a Python dictionary and JSON is dictionaries use single tics for strings and JSON objects use double quotes.]]

 You access the data from your object the exact same way you access a variable of whatever type it is. Since I made dictionaries if I add an item to the dictionary like this:

>>>services.D['catering'] = 'Hourly Rate'

Now to access it you do it the same as a dict or JSON:

>>>print services.D['catering']
Hourly Rate 

Notice the format when we create the object. That is probably the toughest part. We are declaring a variable, using type(), feeding type a string for the name, a tuple for the object type, and an empty dictionary to store stuff.