Working with Python – Class and Object Concept
Introduction
Python is an Object oriented Language. An object contains Propertied and Method and the Class is the blueprint of creating Object. In this Blog post, we are going to discuss about Class and Objects of Python.
How to Create a Class
To create a class we must use
the keyword Class.
Example:
class ExampleClass:
x = 5
In this example we are just create a class named ExampleClass.
How to Create an Object
After creating class, we have to create the Object.
class ExampleClass:
x = 5
a =
ExampleClass()
print(a.x)
In the above example, the
class is as a simplest form. To understand the class, we have to understand the __Init__() function
Understanding the __init__()
Function
Hope, we all have the knowledge of constructor in C++ Language. __init__() function do the same thing as Constructer does.
This function is called automatically when the Object is created. Let us take a
simple example to understand that.
Example:
class ExampleClass:
def __init__(self,
name, age):
self.name
= name
self.age = age
a = ExampleClass("Mayuree", 22)
print(a.name)
print(a.age)
Mayuree
22
Method in the Class
Previously, we checked the Property of the class and now we need
a method in our class.
Example:
class ExampleClass:
def __init__(self,
name, age):
self.name
= name
self.age = age
def myfunc(self):
print("Hello my name is " +
self.name)
a = ExampleClass("Mayuree", 22)
a.myfunc()
Hello my name
is Mayuree
Self Parameters
In the previous example of __init__() constructor, we used self
as a parameters. Question is in mind that what is self parameters.
The self parameter is a reference to the current instance of the
class, and is used to access variables that belongs to the class. It does not
have to be named self, we can call it whatever you like, but it has to be
the first parameter of any function in the class
Delete Object Property
In the above example we have two propertied in the Class object
named “a”. One is “name” and other is “age”. Now we need to delete the age
property.
del a.age
Delete Object
If we need to delete an object.
del a
Hope you like
it.
I have no idea why __init__ is not printed as i tried several time by typing it.
ReplyDeleteHere we are calling the function also in init like a.name and a.age ,isn't it?
ReplyDeleteU can say that. But the Best answer is, Constructor Construct automatically when the object is created.
Delete