Object Oriented - Classes & Objects
Object Oriented
In python, Programmers can create their own objects that have methods and attributes.
In general, Object Oriented programming allows us to create a code that is repeatable and organized.
Class is like an object constructor or a "blueprint" for creating objects.
Create a Class
class myclass:
x = 10
We can use class myclass to create objects
Create a Object
Creating the object o1 and print the value of x
o1 = myclass()
print(o1.x)
Result:
10
The __init__()
function
In order to understand the meaning of classes and how objects can be created using classes, we need to understand the built-in __init__()
function.
__init__
is the constructor of the class. This will be called automatically, when we create object of the class.
All classes will have __init__()
function, which will be executed when the class is being initiated.
This __init__()
function assign properties of a class to the object.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Bhavya", 29)
print(p1.name)
print(p1.age)
Result:
Bhavya
29
The __init__() function is called automatically every time the class is being used to create a new object.
The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
Class Object Attribute
Generally, Attribute is the characteristic of an object. We can specify some characteristics or properties that will be same for any objects of that particular class.
Class Object Attribute
class Circle():
# Class object attribute
pi = 3.14
def __init__(self, radius=1):
self.radius = radius
self.area = self.pi * radius ** 2
Object Methods
Objects can also have methods. Methods in objects are functions that belong to that particular object.
Create a method in the class person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Bhavya", 29)
p1.myfunc()
Result:
Hello my name is Bhavya
Modify Object Properties
We can always modify the object properties.
Modifying the age of the person from 29 to 30
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Bhavya", 29)
p1.age = 30
print(p1.age)
Result:
30
Delete Object properties
We can delete properties of a particular object.
Deleting the age of person p1
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Bhavya", 29)
del p1.age
print(p1.age)
Delete an Object
To delete an object we use del keyword
Deleting the person p1
del p1