Popular Posts

Tuesday, February 21, 2023

Python Class Initiate Method

Hello Python developer!

Hope you're good today with bright sunshine like our future!

Today, I would like to study Initializer method in Python Class.

Class initializer method was made for initiating class variables and methods.

Think about this, if you create an instance from the class and you want it to have each initiate values and functions.


For instance, we will make a calculator Python program. 

First, we will initialize the calculator result variable as 0 with initializer method using ' def __init__(self): ' statement.

Let's look into the following codes.

class Calculator:
def __init__(self):
self.result = 0

def add(self, var1, var2):
self.result = var1 + var2
return self.result

def sub(self, var1, var2):
self.result = var1 - var2
return self.result

test_add = Calculator()
test_sub = Calculator()

print(test_add.add(4, 7))

test_sub.sub(7, 2)
print(test_sub.sub(9,6))





If you want to transfer variables into initializer method, refer following statement.


def __init__(self, var1, var2):
self.first_var = var1
self.second_var = var2


Now, are you familiar with the class 'Initializer' method?

Then, let's analyze following Python exercise codes.

# Python initiate method exercise

class Smartphone:
def __init__(self, model, year): # initiate class 'Smartphone' with following variables and function
self.model = model
self.year = year
self.model_year = model + " " + str(year)


Apple_phone = Smartphone("iPhone 14", 2022)
Samsung_phone = Smartphone("Galaxy S23", 2023)

print(Apple_phone.model, Apple_phone.year)
print(Samsung_phone.model, Samsung_phone.year)

print(Apple_phone.model_year)
print(Samsung_phone.model_year)



Here is above Python source codes in Github(https://github.com/Cevastian/Python-Developer-start-today/blob/master/Python_initiate_method.py)


Hope you get the right answer and level up your Python class understanding.

See you at the next post! Take care! 

No comments:

Post a Comment

Python - Web crawling exercises

Hello Python developer! How are you? Hope you've been good and had wonderful time with Python. There are 10 Python requests module exerc...