[Tutor] definition question

Rodrigues op73418@mail.telepac.pt
Sun Aug 3 07:55:02 EDT 2003


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Kirk Bailey
> Sent: domingo, 3 de Agosto de 2003 6:41
> To: tutor@python.org
> Subject: [Tutor] definition question
>
>
> I am writing a number of functions for my current project,
> and a thought
> occured to me: Are they objects?
>

Everything in Python is an object, therefore a function is an object.
See http://effbot.org/guides/python-objects.htm

>>> def test(*args):
... 	print "Hello, %s!" % str(args)
...

Now, let us inspect what attributes does a function object have:

>>> for elem in dir(test):
... 	print elem
...
__call__
__class__
__delattr__
__dict__
__doc__
__get__
__getattribute__
__hash__
__init__
__module__
__name__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__str__
func_closure
func_code
func_defaults
func_dict
func_doc
func_globals
func_name

In particular:

>>> print test.__class__
<type 'function'>
>>>

You can just continue to poke around function objects and try to see
what those attribuets stand up for -- Python is great for this kind of
exploratory learning.

As you can see a function object has a __call__ method. This is the
method you implement in your classes to make them behave like
functions, e.g.:

>>> class Test(object):
... 	def __init__(self):
... 		pass
... 	def __call__(self):
... 		return "I am %r." % self
...
>>> a = Test()
>>> print a()
I am <__main__.Test object at 0x010DFC50>.
>>>

One last tidbit: as of 2.3 you still cannot inherit from functions --
although, I don't know why would I want to do that anyway.

> This oop stuff still sends me in odd directions and asking strange
> questions. And all the programming I have heretofore
> hammered in was
> procedural, so oop is indeed coming slow and very hard.

Well, if you have any questions, just shoot them.

With my best regards,
G. Rodrigues





More information about the Tutor mailing list