Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multiple self references in arg list 1

Status
Not open for further replies.

taphonomist

Programmer
Jul 21, 2005
11
US
Is it possible to include more than one instance of self in the set of function arguments? As in

def functionForClass(self,firstArg, keyArg=self.stringProductingFunction()):
#do stuff, things
...
return

I keep getting errors with similar code, and was wondering if there was another way around.

Thanks,
D
 
Hi taphonomist,

In this case you get
NameError: name 'self' is not defined

It's because self is the pointer at the instance of your class and it is not known in the time, when your function is created, it will be known first when the instance of your class will be created.
self will be passed to every method as a first argument and you can deal with self-namespace i.e. self.something only in the body of methods.

But what's the reason, that you want to call a member method in an argument list of other member method?
You can do that simply in the body of other method like here:
Code:
[COLOR=#804040][b]class[/b][/color] [COLOR=#008080]MyClass[/color]:
  [COLOR=#804040][b]def[/b][/color] [COLOR=#008080]__init__[/color](self):  
    self.myAttrib = "[COLOR=#ff00ff]my attrib value[/color]"

  [COLOR=#804040][b]def[/b][/color] [COLOR=#008080]stringProductingFunction[/color](self):
    [COLOR=#804040][b]return[/b][/color] "[COLOR=#ff00ff]Bar[/color]"

  [COLOR=#804040][b]def[/b][/color] [COLOR=#008080]functionForClass[/color](self, firstArg, keyArg="[COLOR=#ff00ff]dummy[/color]"):
    secondArg = keyArg
    [COLOR=#804040][b]if[/b][/color] secondArg == "[COLOR=#ff00ff]dummy[/color]":
       secondArg = self.stringProductingFunction()
    [COLOR=#0000ff]# return result  [/color]
    [COLOR=#804040][b]return[/b][/color] firstArg + "[COLOR=#ff00ff]-[/color]" + secondArg

[COLOR=#804040][b]if[/b][/color] __name__=="[COLOR=#ff00ff]__main__[/color]":
  mc = MyClass()
  [COLOR=#804040][b]print[/b][/color] mc.functionForClass("[COLOR=#ff00ff]Foo[/color]")
  [COLOR=#804040][b]print[/b][/color] mc.functionForClass("[COLOR=#ff00ff]Spam[/color]", "[COLOR=#ff00ff]Eggs[/color]")

Output:
Code:
$python pokx.py
Foo-Bar
Spam-Eggs
 
Thanks microm! I came up with a method that used optional arguments, but your solution has the benefit of showing the optional arguments in the function definition. Many ways to the same end, but some make more sense.

More importantly, thanks for the time spent on the explanation!!
D
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top