[Edu-sig] Ditch "self"?

Dethe Elza delza at livingcode.org
Wed Oct 24 06:42:38 CEST 2007


Paul,

to assign a function to an instance object (rather than a class) as a
new method, use the "new" module:

===== start module prototype.py ======


'''
Example of adding methods to an instance object and a class
'''

import new

class Foo(object):

    def bar(self):
        print 'bar', self.__class__


# outside of class Foo, define some functions to turn into methods:

def baz(self):
    print 'baz', self.__class__

def foobar(self):
    print 'foobar', self.__class__

# make some instances

a = Foo()
b = Foo()

# make baz a method of Foo, both a and b should be able to call it

Foo.baz = baz

print 'baz:', Foo.baz

a.baz()
b.baz()

# make foobar a method of a, calling b.foobar should fail

a.foobar = new.instancemethod(foobar, a, a.__class__)

print 'foobar:', a.foobar

a.foobar()
b.foobar() # fails

===== end of module ======

and when you run it:

$ python prototype_based.py
baz: <unbound method Foo.baz>
baz <class '__main__.Foo'>
baz <class '__main__.Foo'>
foobar: <bound method Foo.foobar of <__main__.Foo object at 0x75990>>
foobar <class '__main__.Foo'>
Traceback (most recent call last):
  File "prototype_based.py", line 42, in <module>
    b.foobar() # fails
AttributeError: 'Foo' object has no attribute 'foobar'


More info: http://docs.python.org/lib/module-new.html

HTH

--Dethe


More information about the Edu-sig mailing list