Python Object Oriented
Python is an Object oriented programming Language. This means there exists a concept called ‘class’ that let’s programmer structure the codes of a software in a fashioned way. Because of the use of classes and objects, the programming became easy to understand and code.
Defining Class And Object
A class is a technique to group functions & data members and put them inside a container so that they can be accessed later by using dot (.) operator. Objects are the basic runtime entities of object oriented programming. It defines the instance of a class. Objects get their variables & functions from classes & the class we will be creating are the templates made to create object.
Object Oriented Terminologies
Program For Class In Python
Example:
#!/usr/bin/python
class karl :
varabl = 'Hello'
def function(self) :
print "This is a message Hello"
Another program to explain functions inside class:
Example:
#!/usr/bin/python
class karl(object) :
def __init__(self, x, y):
self.x = x
self.y = y
def sample(self) :
print " This is just a sample code"
In the above code, we created a class name karl using ‘class’ keyword. And two functions are used namely __init__() (for setting the instance variable) & sample(). Classes are used instead of modules because programmers can take this class ‘karl’ & use it or modify it as many times as we want & each one won’t interfere with each other. Importing a module brings the entire program into use.
Creating Objects (Instance Of A Class)
Let’s see an example to show how to create an object:
Example:
#!/usr/bin/pythonclass student:
class student:
def __init__(self, roll, name):
self.r = roll
self.n = name
print ((self.n))
#...
stud1 = student(1, "Alex")
stud2 = student(2, "Karlos")
print (("Data successfully stored in variables"))
Output:
Alex
Karlos
Data successfully stored in variables
Accessing Object Variables
We can access the object’s variable using dot (.) operator.
The syntax is:
The syntax is:
my object_name.variable_name
Example:
print object.varabl
Accessing Attributes
Object attributes can also be accessed by using dot operator.
Example:
stud1.display()
stud2.display()
print " total number of students are: %d" % student.i
Use Of Pre-defined Functions
Instead of using general statements to access attributes, programmers can use the following functions:
Built-In Class Attributes
All the Python built-in class attributes can be accessed using dot (.) operator like other attributes.
The built-in class attributes are:
Comments
Post a Comment