Search code examples
pythonself

Stuck on __init__ and self


I'm pretty new to programming, and I've looked at a bunch of of other questions/answers for a solution to this, but I'm still confused. Could somebody explain it in a very simple way?


Solution

  • When you are creating a class, you need to create a constructor. It is what occurs when you create a new instance of your class. In there, you would maybe have your minimum required arguments passed into the object, and do whatever initialization you need for that object to function as designed.

    SELF is a reference to the variables defined by the class. Note: It is not a reference to variables defined in the method, though you can define new properties for SELF in the function

    class Foo ():
      """This is a dummy class"""
      def __init__(self, a, b, c):
        self.name = a
        self.description = b
        self.total = c
    
      def testMethod(self):
        print("My name is: {} and my Desciption is: {}".format(self.name, self.description))
    

    For more information, feel free to look up the respective documentation for Classes.

    NOTE: for Python 2.7, you need to define a variable object as an object of Foo, because it extends from object. In 3.X, you dont need this.