how to give an object as argument for a method

Marco Herrn herrn at gmx.net
Wed Mar 6 10:25:45 EST 2002


Hi Bertrand,

On Wed, Mar 06, 2002 at 03:07:53AM -0800, Bertrand Geston wrote:
> 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, that was the thing I was serching for. 
So it does have something to do with the 'self' statement. This
statement is not a reserved word, so I have to implement it by myself by
giving it as a parameter to the __init__() method. Am I right there?

> - '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

hmm, do I have to implement that in _every_ method or just in
methods who use the 'self' statement?
I know, the methods work without self, but what is the convention?

> 
> 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.

What does it hurt? It looks good to me. It is just the same as above and
I think that is really good.

[snip]
> ...  def sayNo(self):
> ...   caller = sys._getframe(1).f_locals['self']
this is the only line, that looks a bit ugly. It actually does the same
as when giving caller as parameter. So what can be a reason to implement
it this way? It looks much less readable to me. And I have to say I not
even understand it fully....

So many thanks for your help

Bye
Marco

-- 
If you didn't have to work so hard, you'd have more time to be depressed.

--
Marco Herrn             herrn at gmx.net
(GnuPG/PGP-signed and crypted mail preferred)
Key ID: 0x94620736




More information about the Python-list mailing list