Home »
Python
Python | Demonstrate an example of Class and Object
Here, we are going to demonstrate an example of class and object in Python. How to define a class, declare an object and use it?
Submitted by IncludeHelp, on September 06, 2018
Create a class, and the methods to handle string, like string assignment with "None", hard coded value, with argument in Python.
In this example, there are following methods:
- __init__(self)
Just like a constructor in OOPS concept, this method invokes, when object is going to be created. In this example, string variable msg will be assigned by "None".
- assignValue(self)
This method will assign "Hello world" to msg.
- getValue(self,str)
By using this method, variable msg will be assigned through the value which will be passed from method calling.
- printValue(self)
This method will print the value of variable msg.
Program:
# Python program to demonstrate an
# example of class
class Message(object):
def __init__(self):
# assign none to variable
self.msg = None
def assignValue(self):
# assign any value
self.msg = "Hello World"
def getValue (self,str):
# assign variable with parameter
self.msg = str
def printValue(self):
# print the value
print "msg = ",self.msg
# Main code
# creating object of the class
# Here, M is object nae
M = Message()
# print value
print "value after init. the object..."
M.printValue();
# assign value
M.assignValue()
# print value
print "value after assignValue ()...."
M.printValue();
# assign value using arguemnt
M.getValue("How are you?")
print "value after getValue ()..."
M.printValue();
Output
value after init. the object...
msg = None
value after assignValue ()....
msg = Hello World
value after getValue ()...
msg = How are you?