Python Class and Objects

Python Class and Objects

What is class and object ?

class :- it is a structure which is used to where you put your data and any function that you want 
for example : if you buy any house it is full empty in that room you see a kitchen, bedroom, hall
this we example of class and when you put something in the house like T.V, A.C, Sofa more..
it means you put some value on the class .


in above left image is a class with no value and in right their is a class with value 
for understanding replace class with hall and value with (TV, Sofa etc..)


How we can implement class and object in python ?

To create a class, use the keyword class:

Example :

class Room:  
    total_sofa = 5


this way we create class in python.

How we can access class variable (ex: total_sofa ) value ?

Answer: by using "object"

let me explain don't get confuse 

To create a object, we use:

syntax : object = class_name()

Create an object named p1, and print the value of total_sofa:

Example :

p1 = Room()

print(p1.total_sofa)


How we put value in class ?

Their is 2 ways :

  1.  by using def __init__(): 
  2.  by using DOT(.) operator 


Let we see by using  def __init__() :

All classes have a function called __init__() , which is always executed when the class is being initiated.

Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created

Create a class named Person, use the __init__() function to assign values for name and age:

Example :

class Person:

    def __init__(self, name, age):

         self.name = name

         self.age = age

p1 = Person("John"36)

print(p1.name)


Note: The __init__() function is called automatically every time the class is being used to create a new object.

Let we see by using DOT(.) Operator:

set the age p1.age = 40

Example :

p1.age = 40 


Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

Deleting object parameter :

Delete the age property from the p1 object:

del p1.age

Deleting object :

You can delete objects by using the del keyword:

Delete the p1 object:

del p1

===================================================================

That's it for today hope you like please share it with your friends and family.

Next lecture we see how to work with class function by making one little project.


Thank You 😀😀



Comments

Popular posts from this blog

Fibonacci series in python

exception handling in python