Init Method

__init__ method

define __init__ function

class User():
    name = ""
    pwd = ""

    def __init__(self):
        print("user")

    def sign_up(self):
        print("User Sign Up")

__init__ will be invoked automatically when instantiating a class

user = User()

# __init__ is seldom called this way
user.__init__()
user
user
user.sign_up()
User Sign Up

Only return None

__init__ function can only return a None

class Org():
    def __init__(self):
        return "This is Org"

org = Org()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-4-06eab282d464> in <module>()
      3         return "This is Org"
      4
----> 5 org = Org()


TypeError: __init__() should return None, not 'str'

How to take parameters

  • __init__ function can take parameters, for example
  • __init__ will be invoked automatically
# This is the wrong way to define the class
class Org():

    name = ""
    org_type = ""
    country = ""

    def __init__(self, name, org_type, country):
        # initialize the object attribute
        name = name
        org_type = org_type
        country = country
        print("{} was successfully created!".format(self.name))
# now we must pass parameters to the class Instantiation
bmw = Org()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-6-d0f830f54903> in <module>()
      1 # now we must pass parameters to the class Instantiation
----> 2 bmw = Org()


TypeError: __init__() missing 3 required positional arguments: 'name', 'org_type', and 'country'
bmw = Org("BMW", "Auto", "Germany")

print(bmw.name)
 was successfully created!
  • The above was not our expected result.
  • Nothing was printed, because __init__ has not changed data in our class