11. Building useful classes


#1



Hi there!

Actually I am not stuck and got the way of doing it, but would like to shoot a question in case someone please can help me clarify it.

In this point, for example, what is the benefit from using classes or simply functions. I mean, let's say that I define a function (showed as a comment in the following piece of code). Why do we use a class statement? Wouldn't be enough to use a function statement? Do classes allow us to get more benefits? When? I am sure this is because of theory and there is a useful and logical reason, and would like to understand it well.

Thank you!


class Point3D(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
        
    def __repr__(self):
        return "(%d, %d, %d)" % (self.x, self.y, self.z)

my_point = Point3D(1, 2, 3)

print my_point

# Just function code, instead of the class code
"""
def Point3D(x, y, z):
    return "(%d, %d, %d)" % (x, y, z)
    
my_point = Point3D(1, 2, 3)

print my_point
"""


#2

In this case, it makes sense to just use a function because you only have one function besides init. However, if the class had multiple functions, creating an object would help you group and organize those functions as part of a coherent unit.


#3

Ok, got it, what you say really makes sense. Thank you very much for your reply!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.