Gupta
Gupta

Reputation: 314

Purpose and functionality of Method vs function

I am trying to understand what is the difference between creating a method inside a class and creating a function. Both gives same output. Pls provide clarity

class Point:
    """ Create a new Point, at coordinates x, y """

    def __init__(self, x=0, y=0, z=0):
        """ Create a new point at x, y """
        self.x = x
        self.y = y
        self.z = ((self.x ** 2) + (self.y ** 2)) ** 0.5

and this function:

def distance(x,y):
    z=((x ** 2) + (y ** 2)) ** 0.5
    return z

both looks same to me

p = Point(3,4)
p.x, p.y, p.z

output: (3, 4, 5.0)

and

distance(3,4)

output: 5.0

Upvotes: 0

Views: 56

Answers (4)

ncmathsadist
ncmathsadist

Reputation: 4891

Here is the gist of it. A method can depend on the state (instance) variables in a class. A free function outside of a class has no such dependence.

Example:

>>> x = "foo"
foo
>>> x.length()
3

The method length() has no arguments; however you can see it is dependent on the string's state (its character sequence).

Upvotes: 0

dspr
dspr

Reputation: 2423

With a class you should preferably do something like that :

class Point:
    """ Create a new Point, at coordinates x, y """

    def __init__(self, x=0, y=0):
        """ Create a new point at x, y """
        self.x = x
        self.y = y
   
    def distance(self):
        self.z = ((self.x ** 2) + (self.y ** 2)) ** 0.5
        return self.z

p = Point(3, 4)
print(p.distance())

The main advantage is to avoid the need of passing parameters to the method while they are required for a function

Upvotes: 1

tr4nshum4n
tr4nshum4n

Reputation: 11

It is mostly the same.

Some differences:

  • The function is available to be used outside the class.
  • If you include the calculation in the init constructor, the value is saved as an attribute of the class. It will not be recalculated every time you want to see the value.

Upvotes: 1

tdelaney
tdelaney

Reputation: 77357

The difference is the self reference - the class instance has access to its own local variables and its methods. In this small example there isn't any need for a class. The function returns a tuple object much like the Point object you created. There is a rule: If a class has two methods and one of them is __init__, you shouldn't have a class. In your case, you didn't even reach the two method bar. (That rule is somewhat tongue-in-cheek but applies most of the time).

The usefulness of classes is when you have multiple methods that naturally share a set of data and you want to keep them together. Or if you have different types of objects that share common functionality and you want them to look the same externally.

Upvotes: 2

Related Questions