Basic Exercise on Constructor
« Tutorial on Class Object & Method
- Basic Exercise on Object Oriented Programming
- Create one class student_kit
- Initialize the class by taking name of the student ( constructor ).
-
Display welcome message once any object is created.
Exercise Solution
class student_kit():
def __init__(self,name):
self.name=name
print("Welcome",self.name)
kalu=student_kit("Kalu")
Output
Welcome Kalu
Answer these Questions
- What is the name of the object ?
-
Why the welcome message is printed when we have not called any method to do so?
Extend the above code by adding one method which takes one string input ( section ). How the object can access the instance attribute ?
class student_kit():
def __init__(self,name):
self.name=name
print("Welcome",self.name)
def section(self,s1):
self.section_name=s1 #instance attribute
kalu=student_kit("Kalu") # object declaration
kalu.section('A') # using section method
print(kalu.section_name) # object accessing instance attribute
How the object uses any method or instance attribute
print(kalu.section_name) # instant attribute
print(kalu.section('A') # method
« Tutorial on Class Object & Method
Exercise methods ( basic )»
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com