Page 321 -
P. 321

mobile app development


           JSON can’t handle your custom datatypes


           Unlike pickle, which is smart enough to pickle your custom classes, the
           JSON library that comes with Python isn’t. This means that the standard
           library’s JSON library can work with Python’s built-in types, but not with
           your AthleteList objects.
           The solution to this problem is straightforward: add a method to your
           AthleteList class to convert your data into a dictionary, and send that
           back to the app. Because JSON supports Python’s dictionary, this should work.




                              Let’s create a new method in your AthleteList class. Called to_dict(), your new
                              method needs to convert the class’s attribute data (name, DOB, and top3) into a dictionary. Be
                              sure to decorate your new method with @property, so that it appears to be a new attribute to
                              users of your class.





























           Q:   What’s the purpose of this @property thing again?



          A: The @property decorator lets you specify that a method is to be presented to users of your class as if it were an attribute. If you
           think about things, your to_dict() method doesn’t change the state of your object’s data in any way: it merely exists to return the object’s
           attribute data as a dictionary. So, although to_dict() is a method, it behaves more like an attribute, and using the @property
           decorator let’s you indicate this. Users of your class (that is, other programmers) don’t need to know that when they access the to_dict
           attribute they are in fact running a method. All they see is a unified interface: attributes access your class’s data, while methods manipulate it.


                                                                                      you are here 4    285
   316   317   318   319   320   321   322   323   324   325   326