inheritance question...

Eric Brunel see.signature at no.spam
Mon Jun 23 05:08:43 EDT 2008


Preamble: when posting a brand new question, you'd better not replying to  
an existing completely unrelated message. In most viewers, this will cause  
your message to appear in the thread for the original question and far  
less people will see it. So better create a brand new thread.

On Fri, 20 Jun 2008 23:19:37 +0200, Hamish McKenzie  
<hamish at valvesoftware.com> wrote:
> I have this class:
>
> class Vector(object):
>      TOL = 1e-5
>      def __eq__( self, other, tolerance=TOL ):
>            print tolerance
>
>
> shortened for clarity obviously.  so I want to subclass this class like
> so:
>
> class BigVector(Vector)
>      TOL = 100
>
>
> for example if I was working with large vectors which I knew would never
> be very close hence the large tolerance.  this doesn't work however -
> the TOL class variable, while overridden in BigVector, is still using
> the Vector.TOL variable in the __eq__ method.
>
>
> which kinda makes sense to a certain degree, but how do I get the
> behaviour where doing:
>
> BigVector().__eq__( otherVec )
>
>
> prints 100 instead of 1e-5?
>
> does this question make sense?  not sure how clearly I'm phrasing my
> question...  any of you guys python experts?

There's just no way. The default values for function/method arguments are  
evaluated when the function definition is interpreted. When the __eq__  
method is defined, TOL is 1e-5, so that will be the value used in the  
method, whatever you may do afterwards.

>
> I *could* do this, but its ugly:
>
> class Vector(object):
>      TOL = 1e-5
>      def __eq__( self, other, tolerance=None ):
>            if tolerance is None: tolerance = self.TOL
>            print tolerance

Well, ugliness is in the eye of the beholder... ;-) Even if you find it  
ugly, that's the Python way to do it.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"



More information about the Python-list mailing list