The subclass constructor returns a superclass object

I specialize django.contrib.gis.geos.Point just to better create and handle points with latitude and longitude latitude.

My current code is:

 from django.contrib.gis.geos import Point class LLPoint(Point): def __init__(self, *args, **kwargs): lat = kwargs.get('latitude') lng = kwargs.get('longitude') if lat and lng: super(LLPoint, self).__init__(lng, lat) elif lat or lng: raise TypeError(u'You must both declare latitude and longitude, ' 'not just one of them.') else: super(LLPoint, self).__init__(*args, **kwargs) def __unicode__(self): c = self.coordinates() return u'LLPoint Lat: %.5f Lng: %.5f' % (c['latitude'], c['longitude']) def coordinates(self): return { 'latitude': self.coords[1], 'longitude': self.coords[0] } 

The problem is this:

 >>> LLPoint(latitude=10.0, longitude=20.0) <Point object at 0xdeadbeef> 

Why does it return a Point object? Thus, I cannot use anything that I declared in a subclass. If I try to reproduce the problem using stub classes, this will work. This is probably very stupid, but I do not see.

+4
source share
1 answer

Point.__init__ calls

  super(Point, self).__init__(point, srid=srid) 

which calls GEOSGeometry.__init__ , which calls

  self._post_init(srid) 

which performs

  self.__class__ = GEOS_CLASSES[self.geom_typeid] 

which changes the self class to Point . Evil.


You can try:

 class LLPoint(Point): def __init__(self, *args, **kwargs): ... super(LLPoint, self).__init__(lng, lat) # this changes self.__class__ to Point ... self.__class__ = LLPoint 
+6
source

All Articles