Documente Academic
Documente Profesional
Documente Cultură
Index
14.1.Classes and objects (/communities/aspire-2016/content/classes-and-objects-5)
14.2.Methods (/communities/aspire-2016/content/methods-0)
Go to Doubts
14.2. Methods
A function dened in a class is called a "method". Methods have access to all the data contained on the instance of the object. they can
access and modify anything previously set on self (discussed in 1.2.2.4). Because they use self, they require an instance of the class in order to
be used. For this reason, they're often referred to as "instance methods".
Constructor __init__
The __init__ method is run as soon as an object of a class is instantiated. Its aim is to initialize the object. While creating an instance we need
some values for internal data.
Now,c=Coordinate(3,4)
print c.x,c.y
Prints 3 4 as output
User dened methods are same as function denition but must be dened inside a class.
This example has methods area and perimeter that are used to calculate area and perimeter of an object of the class Rectangle.
self
Each method in a class denition begins with a reference to the instance object. It is by convention named self i.e., methods class access data
via self.
For example above(Rectangle class),
https://campuscommune.tcs.com/communities/aspire-2016/content/methods-0 1/4
28/01/2017 Methods
instantiate object
r=Rectangle(4,5)
r.area() #area() method uses x and y attributes using self
Output would be
123
12345
Destructor
Here,If you observe destructor is called only after reference count of objects reaches zero.
Note: special methods (like ex: __init__ , __del__) start and end with two underscores.
(/communities/aspire-2016/content/classes-and-objects-5)
Previous
(/communities/aspire-2016/content/classes-and-objects-5)
(/communities/aspire-2016/content/python-memory-management-0) (/communities/aspire-2016/content/python-memory- Next
management-0)
Ask a Doubt:
Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune
Note: Please do not use the doubts section for any quiz/quiz-content related queries.
Use the helpline (/feedbacks/new) () located above in top right corner for problems/queries related to quizzes.
Styles Format
https://campuscommune.tcs.com/communities/aspire-2016/content/methods-0 2/4
28/01/2017 Methods
Characters(includingHTML):0
Submit
Reply
Reply
Reply
Reply
Reply
Previous 1 2 (/communities/aspire-2016/content/methods-0?page=2§ion=open)
Next (/communities/aspire-2016/content/methods-0?page=2§ion=open)
https://campuscommune.tcs.com/communities/aspire-2016/content/methods-0 4/4