1

How could I call a self.value in a definition of a function?

class toto :
    def __init__(self):
         self.titi = "titi"
    def printiti(self,titi=self.titi):
          print(titi)
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Bussiere
  • 500
  • 13
  • 60
  • 119
  • 2
    What Python tutorial are you using? – S.Lott Sep 30 '10 at 12:28
  • @S.Lott: what it has to do with py3k? – SilentGhost Sep 30 '10 at 12:33
  • 1
    This question has already been answered here : http://stackoverflow.com/questions/1802971/nameerror-name-self-is-not-defined/1802980#1802980 Try to search first – Franck Sep 30 '10 at 12:34
  • @SilentGhost: The syntax appears to indicate that they're using Python 3.x. Further, comments on @gruszczy answer indicate that the syntax issue confused at least one reader. I tried to make it clear by switching the tags. – S.Lott Sep 30 '10 at 15:13
  • @S.Lott: I see that, but there's nothing py3k-specific about this. OP just happens to use it. – SilentGhost Sep 30 '10 at 15:18
  • @SilentGhost. It may be true that it's applicable more widely. That's not my point. My point is that someone actually was confused by an answer. Since someone actually was confused, I stand by my suggestion to attempt to reduce the potential for confusion through an explicit tag. – S.Lott Sep 30 '10 at 15:24

2 Answers2

6

This is how it is done:

  def printiti(self, titi=None):
    if titi is None:
      titi = self.titi
    print titi

This is a common python idiom (setting default value of argument to None and checking it in method's body).

gruszczy
  • 40,948
  • 31
  • 128
  • 181
2
class Toto:
    def __init__(self):
         self.titi = "titi"

    def printiti(self, titi=None):
         if titi is None:
             titi = self.titi
         print(titi)

Class names are generally Upper Case.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • @Daenyth: I hate parts of PEP8. Compliance is entirely accidental because of copy and paste from the question. Don't thank me. Thank user462794. – S.Lott Sep 30 '10 at 15:15