maksym.ka...@gmail.com schrieb:
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
I think you have a common problem here that occurs when using a script
with more that non-trivial contents as main-script.
What happens is this: you have a
__main__.GeoMap, which is the one tested against in isinstance.
*And* you have a <mainmodule>.GeoMap (replace <mainmodule> with the
actual name) that is imported & used from the other module.
A simple testscript illustrates the issue:
### test.py ####
class Foo(object):
pass
if __name__ == "__main__":
import test
print Foo == test.Foo
Run it from inside the directory you saved it in.
To work around this issue, simply create a bootstrap-main-module that
has not much in it.
Diez
--
http://mail.python.org/mailman/listinfo/python-list