0

If I'm defining a method on an object:

Why does this:

  def forecasts(self, rules = self.rules):
     return rules

give a self not defined error but:

 def forecasts(self, rules=None):                                                                                                                                                                                                         
   if rules is None:                                                                                                                                                                                                                                                      
     rules = self.rules
 return rules

work?

Dimitris Fasarakis Hilliard
  • 136,212
  • 29
  • 242
  • 233
cjm2671
  • 16,836
  • 28
  • 92
  • 144
  • Also duplicate of http://stackoverflow.com/questions/13195989/default-values-for-function-parameters-in-python and http://stackoverflow.com/questions/7371244/using-self-as-default-value-for-a-method and http://stackoverflow.com/questions/8131942/python-how-to-pass-default-argument-to-instance-method-with-an-instance-variab – trincot Feb 18 '17 at 13:42

1 Answers1

0

You're defining a default argument that needs to get evaluated when the function is actually defined.

When Python tries to evaluate that function it is going to try and load a name named self, look-up an attribute on it. and then set it as the default for rules.

You aren't assigning a name for the parameter as you do when you simply use self as a positional, you're actually evaluating an expression, self.rules, which needs self to be defined.

chepner
  • 446,329
  • 63
  • 468
  • 610
Dimitris Fasarakis Hilliard
  • 136,212
  • 29
  • 242
  • 233