[Q] __init__ in class

Irv Kalb Irv at furrypants.com
Thu Dec 26 16:58:32 EST 2019


> On Dec 26, 2019, at 3:11 AM, 황병희 <soyeomul at doraji.xyz> wrote:
> 
> in making class, why we should set "__init__"? so non-init class is
> useless? actually i did fail to understand __init__'s meaning. what is
> role of __init__ in class.
> 
> sincerely, from python beginner.
> 
> -- 
> ^고맙습니다 _地平天成_ 감사합니다_^))//
> -- 
> https://mail.python.org/mailman/listinfo/python-list

Whenever you create object from a class, you use the name of the class in a statement like this:

myObject = MyClass()   #  "MyClass" would be the name of a class in your code

When you run a line like the one above, Python looks to see if that class has a method named __init__().  If it does, then Python calls that method of the newly created object.  In that method you typically put the initialization of any instance variables that you want to use in other methods, and include any additional code that you only want to run when an object is created from the class.  While it is not required to have an __init__() method in a  class, it is generally considered good practice to have one.  

As an example, let's say that you create a point class, where the Point has both an x and a yY value.  Your class might look like this:

class Point:
    def __init__(self, x, y):   # When you create a Point object, you must pass in a value for x and y
        self.x = x
        self.y = y

    #Then you would probably have other methods like:

    def getX(self):
        return self.x

     def getY(self):
         return self.y

     def show(self):
          print('The values of this point are:', self.x, self.y)

etc.

Given a class like that, when you create an object from the Point class, you pass in values for x and y.  The code in the __init__() method saves away those values into instance variables.  Those instance variables can be used by other methods.  In this example class, getX, getY, and show.

Here is some sample code to create two Point objects, then ask them to show their contents:

pointA = Point(10, 15)
pointB = Point(-3, 38)
pointA.show()  
printB.show()

When run, this will print:

The values of this point are: 10, 15
The values of this point are: -3, 38

Hope that gives you a start in the world of OOP.

Irv



More information about the Python-list mailing list