Saturday, February 23, 2013

Function or method

Lately I have been reading about Python. Here is an example that shows some interesting properties of functions and methods.
Given this code in methods.py

def f(a):
    print a
 
class C:
    def __init__(self, x):
        self.x = x
 
    def __str__(self):
        return "C(%d)" % self.x


Let's try some statements in the Python console

>>> from methods import *
>>> f("Hello")
Hello
>>> c = C(5)
>>> print c
C(5)
>>> c.f = f
>>> c.f("bye")
bye
>>> C.g = f
>>> c.g()
C(5)
>>> g = c.g
>>> g()
C(5)



1 comment:

  1. As I am not a Python expert, it took me some time to figure out what is happening in the code above. Do you have more puzzles like this one? ;-)

    ReplyDelete