python newbie

Duncan Booth duncan.booth at invalid.invalid
Sat Nov 3 08:49:21 EDT 2007


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> 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__
>>> foo.bar(42)
In method bar of <module 'foo' (built-in)>, param=42
>>> foo.baz(42)
Function baz, param=42
>>> foo.bar
<bound method MyModule.bar of <module 'foo' (built-in)>>
>>> foo.baz
<function baz at 0x01160830>
>>> help(foo)
Help on module foo:

NAME
    foo - This is the foo module

FILE
    (built-in)


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



More information about the Python-list mailing list