python newbie

Duncan Booth duncan.booth at invalid.invalid
Sat Nov 3 13:49:21 CET 2007

Steven D'Aprano <steve at> wrote:

>> Then if foo is a class, we probably all agree that bar is a method of
>> foo.
> There are funny edge cases (e.g. bar might be an attribute with a 
> __call__ method) but in general, yes, bar would be a method of foo.
But that 'funny edge case' is exactly the point here: if foo is a module 
then bar probably is an attribute with a __call__ method.

modules are not special in any way, except that you cannot subclass them. 
Oops, sorry I got that wrong. Modules are not special in any way, they can 
have methods as well as functions:

>>> import string
>>> class MyModule(type(string)):
	def bar(self, param):
		print "In method bar of %r, param=%r" % (self, param)

>>> foo = MyModule('foo', 'This is the foo module')
>>> exec """def baz(param):
   print "Function baz, param=%r" % (param,)
""" in foo.__dict__
In method bar of <module 'foo' (built-in)>, param=42
>>> foo.baz(42)
Function baz, param=42
<bound method of <module 'foo' (built-in)>>
>>> foo.baz
<function baz at 0x01160830>
>>> help(foo)
Help on module foo:

    foo - This is the foo module


>>> foo.__file__=''
>>> foo
<module 'foo' from ''>
>>> sys.modules['foo'] = foo
>>> del foo
>>> import foo
In method bar of <module 'foo' from ''>, param='hello'

More information about the Python-list mailing list