Don't understand this "method mapping"

Bas Michielsen BMichielsen at compuserve.com
Sat Jul 21 09:15:05 EDT 2001


## Hello,

## I am a beginner with Python and I don't understand why in the code
below
## the attribute `map' first represents Curve.linear which also
## points to the external function linear and then, after calling
set_map,
## is simply the external function linear for a Curve object.
## I had expected that calling Curve.linear would be signalled as an
## attribute error because there is no method linear in class Curve or
## otherwise that the two ways to initialise the map attribute would be
## equivalent???
##
## Is somebody able and willing to explain this to me,

def linear( x_in, a=0): # a=0 is a stub to get past an error condition
    print "linear called, a =", a
    return x_in

class Curve:
    map = linear 

    def use_map( self, x):
        print "Using self.map = ", self.map
        self.y = self.map( x)

    def set_map( self):
        self.map = linear
        
# Test code (I am running Python 1.5.2)

c = Curve()
print c.map
c.use_map( 1.0)
print c.y
c.set_map()
c.use_map( 1.0)
print c.y

## # Output produced by the above
## <method Curve.linear of Curve instance at 80c7380>
## Using self.map =  <method Curve.linear of Curve instance at 80c7380>
## linear called, a = 1.0
## <__main__.Curve instance at 80c7380>
## Using self.map =  <function linear at 80b6dd0>
## linear called, a = 0
## 1.0

-- 
Bas Michielsen
14, avenue du Corail
31650 St. Orens de Gameville
France



More information about the Python-list mailing list