On Feb 12, 11:53 am, maksym.ka...@gmail.com wrote:
> Hi there.
> now i'm a complete newbie for python, and maybe my problem is stupid
> but i cannot solve it myself
>
> i have an object of class GeoMap which contains lists with objects of
> GeoMapCell (i will not explain what they should do, hope its not
> important). Then i want to serialize these objects to json notation.
> So i imported json module and as shown in docs for it extended
> JSONEncoder class.  Look at the code below
>
> ##main module
> from worldmap import GeoMap, GeoMapCell
>
> import testdata
> import json
>
> class GeoMapEncoder(json.JSONEncoder):
>     def default(self, obj):
>         if isinstance(obj, GeoMap):
>             return None
>         return json.JSONEncoder.default(self, obj)
>
> def main():
>     print(json.dumps(2 + 5j, cls=ComplexEncoder))
>
>     geomap = testdata.createTestMap()
>     print(json.dumps(geomap, cls=GeoMapEncoder))
>     pass
>
> if __name__ == '__main__':
>     main()
>
> ===========
>
> ##worldmap module
> class GeoMap:
>     cells = []
>     activerow = 0
>     activecol = 0
>
>     def addCell(self, acell):
>         if len(self.cells) == 0:
>           self.cells.append([])
>           self.activerow = 0
>         acell.col = self.activerow
>         acell.row = self.activecol
>         self.cells[self.activerow].append(acell)
>         self.activecol += 1
>
>     def addRow(self):
>         self.cells.append([])
>         self.activerow += 1;
>         self.activecol = 0;
>
> class GeoMapCell:
>     neighbours = (None, None, None, None, None, None, )
>     col = 0
>     row = 0
>
> The problem is in here.
>
> class GeoMapEncoder(json.JSONEncoder):
>     def default(self, obj):
>         if isinstance(obj, GeoMap):  ## <=======   isinstance doesnot
> work as i expected
>             return None
>         return json.JSONEncoder.default(self, obj)
>
>  Though obj is object of GeoMap class, isinstance returns False. Where
> was i mistaken. If i shouldn't use isinstance, then what function
> would check class of object?
>
> Oh, maybe its important. I'm working on WinXP SP3, Python 3.0, IDE -
> PyScript

Here's a crazy idea out of left field.  Just before calling
isinstance, why not try:

print(type(obj))
print(str(obj))

This may illuminate the unexpected behavior, you'll find out just what
obj has in it.

-- Paul
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to