"self" - a python wart or "feature"
Mongryong
Mongryong at sympatico.ca
Mon Feb 17 17:13:34 EST 2003
On Mon, 2003-02-17 at 00:16, Cere Davis wrote:
> Thanks but I'm having diffuculty understanding how this FAQ answers my
> question about requiring self as the first argument in a function.
> I can appreciate clarity of scope for variables but it seems to me that
> requiring an extra argument in a function that is allready indented into
> the class
> to be unnecessary. From what little I know about Ruby, it does not
> require this for function declarations within a class.
Consider this example:
class Receiver:
def __init__(self, x):
self.x = x
def execute(self):
self.x = self.x + 1
return self.x
class Caller:
def __init__(self, func, arg):
self.func = f
self.arg = arg
def run(self):
return self.f(arg)
class Struct:
pass
def rxFunc(arg):
arg.x = arg.x + 1
return arg.x
ex#1
>>> obj = Struct()
>>> obj.x = 3
>>> tx = Caller(rxFunc, obj)
>>> tx.run()
4
ex#2
>>> obj = Receiver(3)
>>> tx = Caller(Receiver.execute, obj)
>>> tx.run()
4
ex#3
>>> obj = Struct()
>>> obj.x = 3
>>> tx = Caller(Receiver.execute, obj)
>>> tx.run()
4
ex#4
class Receiver2(Receiver):
def __init__(self, x, y):
self.x = x
self.y = y
def execute (self): # overrides Receiver.execute
z = self.x + self.y
return z
>>> rx2 = Receiver(1,2)
>>> rx2.execute()
3
>>> Receiver.execute(rx2)
2
>>> rx2.x
2
That's what Python allows you to do. This feature allows one to develop
'callback' code that supports both 'classes' and 'procedural' style
programming. As ex#3 and ex#4 show, this feature also allows one to
'mix' code. In a way, Python's OO support is much closer to how OO is
done in C.
More information about the Python-list
mailing list