I'm thinking about how, in Ruby, class definitions are never closed, meaning
you can add methods to a script in various locations. You don't supersede
the old class def when you reopen it for more stuff. There's also this idea
of defining a module full of methods and then binding those to a class -- I
haven't really learned this fully yet.
In Python, we have the ability to define methods externally to classes, as
ordinary functions, except we need the implicit 'self' variable as a first
argument. For example:
>>> def __init__(self, a,b):
self.a = a
self.b = b
>>> def __repr__(self):
return 'Duh object (%s, %s)' % (self.a, self.b)
>>> class Duh(object):
pass
>>> Duh.__init__ = __init__
>>> Duh.__repr__ = __repr__
>>> o = Duh(1,2)
>>> o
Duh object (1, 2)
Or we could do it this way:
>>> class Duh2(object):
__init__ = __init__
__repr__ = __repr__
>>> o = Duh2(3,4)
>>> o
Duh object (3, 4)
Why do it this way? I suppose you might have several classes that all use
some method. Define the method once, then shove it into more than one
gutless class.
In the above case, I guess there's no reason to use underunder syntax in the
external function name, given the rebinding to a local attribute at runtime.
I.e. we might as well go:
>>> def representer(self):
return 'Duh object (%s, %s)' % (self.a, self.b)
>>> class Duh(object):
pass
>>> Duh.__init__ = constructor
>>> Duh.__repr__ = representer
>>> o = Duh(9,10)
Duh object (9, 10)
Kirby
_______________________________________________
Edu-sig mailing list
[email protected]
http://mail.python.org/mailman/listinfo/edu-sig