Python Object Oriented Programming

Python supports object oriented programming like other programming languages. All classes are used to create user defined data types.

Syntax:
class classname:
Classmemebrs

The first string is called docstring and has a brief description about the class. Although not mandatory, this is recommended.

A class creates a new local namespace where all its attributes are defined. Attributes may be data or functions.
There are also special attributes in it that begins with double underscores (__). For example, __doc__ gives us the docstring of that class.

self

Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self.

The self in Python is equivalent to the this pointer in C++ and the this reference in Java and C#.

 

Programe on classes and objects

class sample:
a=10
def put(self):
print("welcome to oops")

x=sample()
x.put()
print(x.a)

program to find the sum of 2numbers

class sample:

def get(self):
self.a=10
self.b=20

def put(self):
print("Sum",self.a+self.b)

x=sample()
x.get()
x.put()

 

program to find the sum of 2nos by passthe arguments

class sample:

def get(self,x,y):
self.a=x
self.b=y

def put(self):
print("Sum",self.a+self.b)

x=sample()
x.get(3,2)
x.put()

find the sum of 2nos by passing arguments and return value

class sample:

def get(self,x,y):
self.a=x
self.b=y

def put(self):
return self.a+self.b

x=sample()
x.get(3,2)
k=x.put()
print("sum of 2nos",k)

 

 

For
More Explanation
&
Online Classes

Contact Us:
+919885348743