Python OOPs Concepts
Object
An object is an entity that has attributes and behaviour. For example,Ram
is an object who has attributes such as height, weight, color etc. and
has certain behaviours such as walking, talking, eating etc.Class
A class is a blueprint for the objects. For example, Ram, Shyam, Steve, Rick are all objects so we can define a template (blueprint) classHuman
for these objects. The class can define the common attributes and behaviours of all the objects.Methods
As we discussed above, an object has attributes and behaviours. These behaviours are called methods in programming.Example of Class and Objects
In this example, we have two objectsRam
and Steve
that belong to the class Human
Object attributes: name, height, weight
Object behaviour: eating()
Also read: How to create class and objects in Python.
Source code
class Human: # instance attributes def __init__(self, name, height, weight): self.name = name self.height = height self.weight = weight # instance methods (behaviours) def eating(self, food): return "{} is eating {}".format(self.name, food) # creating objects of class Human ram = Human("Ram", 6, 60) steve = Human("Steve", 5.9, 56) # accessing object information print("Height of {} is {}".format(ram.name, ram.height)) print("Weight of {} is {}".format(ram.name, ram.weight)) print(ram.eating("Pizza")) print("Weight of {} is {}".format(steve.name, steve.height)) print("Weight of {} is {}".format(steve.name, steve.weight)) print(steve.eating("Big Kahuna Burger"))Output:
Height of Ram is 6 Weight of Ram is 60 Ram is eating Pizza Weight of Steve is 5.9 Weight of Steve is 56 Steve is eating Big Kahuna Burger
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.