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.


# 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..."

# assign value 

# print value 
print "value after assignValue ()...."

# assign value using arguemnt
M.getValue("How are you?")
print "value after getValue ()..."


value after init. the object...
msg =  None
value after assignValue ()....
msg =  Hello World
value after getValue ()...
msg =  How are you?

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.