User Tools

Site Tools


help:python:data_class

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
help:python:data_class [2020/08/11 14:47] – [Data Class in Python] gerhardhelp:python:data_class [2020/08/11 15:04] (current) – [Data Class in Python] gerhard
Line 22: Line 22:
  
  
-Also note the ``__iter__`` function is the classes and the ``yield`` instead of return that allows iteration in the __iter__ function without the need for a __next__ function.+Also note the ''__iter__'' function is the classes and the ''yield'' instead of ''return'' that allows iteration in the ''__iter__'' function without the need for a ''__next__'' function inside the class.
  
 <code python> <code python>
Line 55: Line 55:
  
 </code> </code>
 +
 +The 'main' function then instantiates the data class that now contains a and b in c.
 +
 +Data is then type casted to a dictionary that yields the key/value pairs in the for loop and prints them to the console.
  
 <code json> <code json>
Line 64: Line 68:
 </code> </code>
  
 +<WRAP center round tip 60%>
 +The really cool feature of this approach is the ability to keep on dynamically adding variables and getting the iterator to expose them dynamically without knowing what is in the class when passed between functions or even applications.
 +
 +This approach also sets up the class for passing on json strings between applications with very little code required to prepare the string. 
 +
 +</WRAP>
 +
 +<code python>
 +
 +import json
 +
 +json.dumps(dict(data),indent=2)
 +
 +</code>
 +
 +The resulting output is:
 +
 +<code json>
 +{
 +  "c": {
 +    "val3": 789,
 +    "str3": "ghi"
 +  },
 +  "a": {
 +    "val1": 123,
 +    "str1": "abc"
 +  },
 +  "b": {
 +    "val2": 456,
 +    "str2": "def"
 +  }
 +}
 +</code>
  
help/python/data_class.1597157231.txt.gz · Last modified: 2020/08/11 14:47 by gerhard