Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. import json
  2.  
  3.  
  4. class Ingredient:
  5.     def __init__(self, _name=None, _weight=None):
  6.         self.name = _name
  7.         self.weight =_weight
  8.  
  9.     def __init__(self, **entries):
  10.         self.__dict__.update(entries)
  11.  
  12.     def to_json(self):
  13.         data = json.dumps(vars(self), indent=4)
  14.         with open("out_ingz.json", "w+") as f:
  15.             f.write(data)
  16.         return data
  17.  
  18.     def build_object_json(self, **data):
  19.         self.__dict__ = **data
  20.  
  21. class Pica:
  22.     def __init__(self, ingz=[]):
  23.         self.ingredients = ingz
  24.  
  25.     def build_object_json(self, data):
  26.         for i in data['ingredients']:
  27.             self.ingredients.append(Ingredient.build_object_json(i))
  28.  
  29.     def __str__(self):
  30.         return f'{self.ingredients}'
  31.  
  32.     def to_json(self):
  33.         p = self
  34.         for i in range(len(p.ingredients)):
  35.             p.ingredients[i] = p.ingredients[i].__dict__
  36.         data = json.dumps(vars(self), indent=4)
  37.         with open("out_pica.json", "w+") as f:
  38.             f.write(data)
  39.         return data
  40.  
  41.     def from_json(self, file):
  42.         with open(file, "r") as f:
  43.             data = json.loads(f.read())
  44.         self.build_object_json(data)
  45.         # for i in data['ingredients']:
  46.         #     self.ingredients.append(json.loads(i))
  47.  
  48.  
  49. if __name__ == "__main__":
  50.     # i1 = Ingredient('tomato', 20)
  51.     # i2 = Ingredient('cheese', 50)
  52.     # p = Pica([i1, i2])
  53.     # p.to_json()
  54.  
  55.     p = Pica()
  56.     p.from_json('out_pica.json')
  57.     print(p)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement