Python Language / Python Classes and Objects

Class is a collection of Attribute/properties and instance functions/methods. Object is a real world thing / entity. Classes attributes and instance methods are accessed using object.

Sample Programs
Program Example
#Create a class and with its object and having a attribute y and prints its value using the object.

class ourClass:
 y = 10
class ourClass:
 obj1 = ourClass ()
 print(obj1.y)

10


The __init__() Function
It is called automatically every time the class is being used to create a new object and is used to assign values to object properties.

Sample Programs
Program Output
#use __init__() to give values to variables.

class Fruits:
 def __init__(self, name, price):
  self.name = name
  self.price = price
obj1 = Fruits("Mango", 50)
print(obj1.name)
print(obj1. price)

Mango
50


Object Methods
Class is a collection of Attribute/properties and instance functions/methods. Object is a real world thing / entity. Classes attributes and instance methods are accessed using object.

Example

Program Output
class Fruits:
 def __init__(self, Fruitname, price):
  self.Fruitname = Fruitname
  self.price = price
 def ourfunc (self):
  print("Fruit Name: " + self.Fruitname)
  print("Fruit Price: " + self.price)
p1 = Fruits("Apple", "20")
p1.ourfunc()
Fruit Name: Apple
Fruit Price: 20
class Fruits:
 def __init__(obj1, Fruitname, price):
  obj1.Fruitname = Fruitname
  obj1.price = price
 def ourfunc (obj1):
  print("Fruit Name: " + obj1.Fruitname)
  print("Fruit Price: " + obj1.price)
p1 = Fruits("Apple", "20")
p1.ourfunc()
Fruit Name: Apple
Fruit Price: 20
#Modify Object Properties
class Fruits:
 def __init__(obj1, Fruitname, price):
  obj1.Fruitname = Fruitname
  obj1.price = price
 def ourfunc (obj1):
  print("Fruit Name: " + obj1.Fruitname)
  print("Fruit Price: " + obj1.price)
p1 = Fruits("Apple", "20")
p1.ourfunc()
p1.price="90"
p1.ourfunc()
Fruit Name: Apple
Fruit Price: 20
Fruit Name: Apple
Fruit Price: 90
#Delete Object Properties using del keyword
class Fruits:
 def __init__(obj1, Fruitname, price):
  obj1.Fruitname = Fruitname
  obj1.price = price
 def ourfunc (obj1):
  print("Fruit Name: " + obj1.Fruitname)
p1 = Fruits("Apple", "20")
p1.ourfunc()
del p1.price
p1.ourfunc()
Fruit Name: Apple
Fruit Name: Apple
#Delete Object using del keyword
class Fruits:
 def __init__(obj1, Fruitname, price):
  obj1.Fruitname = Fruitname
  obj1.price = price
 def ourfunc (obj1):
  print("Fruit Name: " + obj1.Fruitname)
p1 = Fruits("Apple", "20")
p1.ourfunc()
del p1.price
p1.ourfunc()
del p1


Home     Back