0% found this document useful (0 votes)
92 views7 pages

What Is The Difference Between Function and Method? Explain The Working of The Init Method With Suitable Code

The document discusses the difference between functions and methods in Python. It defines methods as being associated with an object and implicitly passed the object as the first argument (self). Methods can access instance variables of the class. Functions are independent of classes and are not implicitly passed an object. The init method is explained as similar to constructors in other languages, used to initialize an object's state when it is created. An example init method is provided.

Uploaded by

Likhith M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views7 pages

What Is The Difference Between Function and Method? Explain The Working of The Init Method With Suitable Code

The document discusses the difference between functions and methods in Python. It defines methods as being associated with an object and implicitly passed the object as the first argument (self). Methods can access instance variables of the class. Functions are independent of classes and are not implicitly passed an object. The init method is explained as similar to constructors in other languages, used to initialize an object's state when it is created. An example init method is provided.

Uploaded by

Likhith M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

4. What is the difference between function and method?

Explain
the working of the init method with suitable code.

A] METHOD
Python Method
1. Method is called by its name, but it is associated to an
object (dependent).
2. A method is implicitly passed the object on which it is invoked.
3. It may or may not return any data.
4. A method can operate on the data (instance variables) that is
contained by the corresponding class

Basic Method Structure in Python :


# Basic Python method
class class_name
def method_name () :
......
# method body
......
User defined method
# Python 3 User-Defined Method
class ABC :
def method_abc (self):
print("I am in method_abc of ABC class. ")

class_ref = ABC() # object of ABC class


class_ref.method_abc()
OUTPUT
I am in method of ABC class.
B] FUNCTIONS

Functions
1. Function is block of code that is also called by its name.
(independent)
2. The function can have different parameters or may not have any at
all. If any data (parameters) are passed, they are passed
explicitly.
3. It may or may not return any data.
4. Function does not deal with Class and its instance concept.

Basic Function Structure in Python :


def function_name ( arg1, arg2, ...) :
......
# function body
......
User defined function
def Subtract (a, b):
return (a-b)
print( Subtract(10, 12) ) # prints -2
print( Subtract(15, 6) ) # prints 9

OUTPUT
-2
9

1. Simply, function and method both look similar as they perform in


almost similar way, but the key difference is the concept of ‘Class
and its Object‘.
2. Functions can be called only by its name, as it is defined
independently. But methods can’t be called by its name only, we
need to invoke the class by a reference of that class in which it is
defined, i.e. method is defined within a class and hence they are
dependent on that class.

INIT METHOD
The __init__ method is similar to constructors in C++ and Java.
Constructors are used to initialize the object’s state. The task of constructors
is to initialize(assign values) to the data members of the class when an
object of class is created. Like methods, a constructor also contains
collection of statements(i.e. instructions) that are executed at time of Object
creation. It is run as soon as an object of a class is instantiated. The method
is useful to do any initialization you want to do with your object.
Example:
# A Sample class with init method
class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()

OUTPUT
Hello, my name is Nikhil

5. What are Container classes? Explain with suitable


examples.

Designing New Container Classes :


While Python provides a diverse set of container classes, there will always be a
need to develop container classes tailored for specific applications. We
illustrate this with a class that represents a deck of playing cards and also with
the classic queue container class.
Designing a Class Representing a Deck of Playing Cards:
In the blackjack program, the deck of cards was implemented using a list. To
shuffle the deck, 264 Chapter 8 Object-Oriented Programming we used the
shuffle() method from the random module, and to deal a card, we used the list
method pop(). In short, the blackjack application was written using non
application specific terminology and operations. The blackjack program would
have been more readable if the list container and operations were hidden and
the program was written using a Deck class and Deck methods. So let’s develop
such a class. But first, how would we want the Deck class to behave? First, we
should be able to obtain a standard deck of 52 cards using a default
constructor: >>> deck = Deck() The class should support a method to shuffle
the deck: >>>deck.shuffle() The class should also support a method to deal the
top card from the deck. >>>deck.dealCard() Card('9', '♠') >>>deck.dealCard()
Card('J', '♦') >>>deck.dealCard() Card('10', '♦') >>>deck.dealCard() Card('8', '♣')
The methods that the Deck class should support are: • Deck(): Constructor that
initializes the deck to contain a standard deck of 52 playing cards • shuffle():
Shuffles the deck • getSuit(): Pops and returns the card at the top of the deck.

Implementing the Deck (of Cards) Class:


Let’s implement the Deck class, starting with the Deck constructor. Unlike the
two examples from the previous section (classes Point and Card), the Deck
constructor does not take input arguments. It still needs to be implemented
because its job is to create the 52 playing cards of a deck and store them
somewhere. To create the list of the 52 standard playing cards, we can use a
nested loop that is similar to the one we used in function shuffledDeck() of the
blackjack application. There we created a set of suits and a set of ranks suits =
{'\u2660', '\u2661', '\u2662', '\u2663'} ranks =
{'2','3','4','5','6','7','8','9','10','J','Q','K','A'} and then used a nested for loop to
create every combination of rank and suit for suit in suits: for rank in ranks: #
create card with given rank and suit and add to deck We need a container to
store all the generated playing cards.
Now we have some design decisions to make. First, should the list containing
the playing cards be an instance or class variable? Because every Deck object
should have its own list of playing cards, the list clearly should be an instance
variable. We have another design question to resolve: Where should the sets
suits and ranks be defined? They could be local variables of the __init__()
function. They could also be class variables of the class Deck. Or they could be
instance variables. Because the sets will not be modified and they are shared
by all Deck instances, we decide to make them class variables. Take a look at
the implementation of the method __init__() in module cards.py. Since the
sets suits and ranks are class variables of the class Deck, they are defined in
namespace Deck. Therefore, in order to access them in lines 12 and 13, you
must specify a namespace: for suit in Deck.suits: for rank in Deck.ranks: # add
Card with given rank and suit to deck We now turn our attention to the
implementation of the two remaining methods of class Deck. The method
shuffle() should just call random module function shuffle() on instance variable
self.deck
EXAMPLE:
1. from random import shuffle
2. class Deck:
3. 3'represents a deck of 52 cards'
4. # ranks and suits are Deck class variables
5. ranks = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'}
6. # suits is a set of 4 Unicode symbols representing the 4 suits 9 suits = {'\
u2660', '\u2661', '\u2662', '\u2663'}
7. def __init__(self):
8. 'initialize deck of 52 cards'
9. self.deck = [] # deck is initially empty
10. for suit in Deck.suits: # suits and ranks are Deck
11. for rank in Deck.ranks: # class variables
12. # add Card with given rank and suit to deck
13. self.deck.append(Card(rank, suit))
14. defdealCard(self):
15. 'deal (pop and return) card from the top of the deck'
16. returnself.deck.pop()
17. def shuffle(self):
18. 'shuffle the deck'
19. shuffle(self.deck)

6.Write a note on User defined exceptions .


In Python, users can define custom exceptions by creating a new class.
This exception class has to be derived, either directly or indirectly, from the
built-in  Exception  class. Most of the built-in exceptions are also derived from
this class.

EXAMPLE 1

>>> class CustomError(Exception):


... pass
...

>>> raise CustomError


Traceback (most recent call last):
...
__main__.CustomError

>>> raise CustomError("An error occurred")


Traceback (most recent call last):
...
__main__.CustomError: An error occurred

Here, we have created a user-defined exception called  CustomError  which


inherits from the  Exception  class. This new exception, like other exceptions,
can be raised using the  raise  statement with an optional error message.
EXAMPLE 2
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# you need to guess this number
number = 10
# user guesses a number until he/she gets it right
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")

We have defined a base class called  Error .


The other two exceptions ( ValueTooSmallError  and  ValueTooLargeError ) that are
actually raised by our program are derived from this class. This is the
standard way to define user-defined exceptions in Python programming,
but you are not limited to this way only.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy