how to give an object as argument for a method

Bertrand Geston bergeston at yahoo.fr
Wed Mar 6 06:07:53 EST 2002


If I understand your question correctly, you can do it like in java:

>>> class Spam:
...  def sayYesBut(self, caller):
...   print "Yes %s, but I'm %s !" % (caller, self)
...
>>> class Egg:
...  def __init__(self):
...   self.spam = Spam()
...  def saySomething(self):
...   self.spam.sayYesBut(self)
...
>>> egg = Egg()
>>> egg.saySomething()
Yes <__main__.Egg instance at 0x01227338>, but I'm <__main__.Spam instance
at 0x0125CC88> !
>>>

But:
- 'self' is used in Python in place of 'this' in java
- 'self' is mandatory (no implicit reference to the instance)
- 'self' is not a reserved word but a **STRONG** naming convention for the
first argument of every method that always refer to the instance

PS. Here is a way to do it magically. It comes from the excellent post 'Get
reference to "owner"' from ... yesterday ! This is powerfull and funny but
IMHO it hurts good principles of design.

>>> class Egg:
...  def __init__(self):
...   self.spam = Spam()
...  def saySomething(self):
...   self.spam.sayYesBut(self)
...  def saySomethingElse(self):
...   self.spam.sayNo()
...
>>> class Spam:
...  def sayYesBut(self, caller):
...   print "Yes %s, but I'm %s !" % (caller, self)
...  def sayNo(self):
...   caller = sys._getframe(1).f_locals['self']
...   print "No %s, but I'm %s !" % (caller, self)
...
>>> egg = Egg()
>>> egg.saySomething()
Yes <__main__.Egg instance at 0x0126E098>, but I'm <__main__.Spam instance
at 0x010F7DA8> !
>>> egg.saySomethingElse()
No <__main__.Egg instance at 0x0126E098>, but I'm <__main__.Spam instance at
0x010F7DA8> !
>>>

B.

Marco Herrn <herrn at gmx.net> wrote in message news:<mailman.1015366993.15304.python-list at python.org>...
> Hello,
> 
> I am new to python and have a question how to achieve $subject.
> 
> I want something like the 'this' statement in java that gives you the
> current object. So when I call a method like f(this) I give the object
> that calls the method as argument.
> But how can I do this in python?
> I am using python 2.1.
> 
> Bye
> Marco
> -- 
> This life is a test.  It is only a test.  Had this been an actual life, you
> would have received further instructions as to what to do and where to go.



More information about the Python-list mailing list