Search code examples
pythonclassfunctionself

How to call a self.value in a class function definition in python?


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)

Solution

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