OOP In Python .1

Python is an object oriented programming language every thing in python is object and it have its own properties and methods. The OOP concept focuses on reusable code.

Class

A class is blueprint or template of an objects every class has its own properties and methods a class can be made in python with following syntax.

The simple class definition will look like this

class ClassName:
  statement-1
  .
  .
  .
  statement-N

For defining a class we start it with the name class and than add class name the first character of class name will be capital than add colon, after colon on new line the class inner block will be started than we add ident of whitespaces minimum of one space “Ident is required in python for function, loops, conditions and classes e.t.c. after ident we can put properties and methods with same ident for example a class with some properties will looks like this.

class Fruit:
  name = "Apple"
  weight = "2kg"

So, this is a simple class with the name “Fruit” and have 2 properties.

Objects

An object is an instantiation of a class, When we define a class it is only a template or blue print. After creating a object we can access the properties of that class and can also call that’s class methods. A class can have as many objects as many a user need. Every new object can have different values.

How to create an object

An object can be created by calling a class name like a function and than assign it to a variable now an object of that class is stored in that variable after that we can implement all the methods and properties of class with this variable name For Example.

class Fruit:
  name = "Apple"
  weight = "2kg"

new_fruit = Fruit()

Above given code will create an object of Fruit class now we can access the properties of Fruit class by variable new_fruit like

print(new_fruit.name)
print(new_fruit.weight)
First Line of code will print Apple
Second Line of code will print 2KG

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s