Creating a class


#1

Hello everyone, I am currently learning python on Codecademy. I am stuck at an exercise which can be reached through the following link.

https://www.codecademy.com/courses/python-intermediate-en-egNXj/1/5?curriculum_id=4f89dab3d788890003000096

The question is not very difficult. I just need to create a class and define some methods in it. I wrote the following code:-

class Point3D(object):
    def __init__(self,x,y,z):
        self.x=x
        self.y=y
        self.z=z
    def __repr__(self):
        string="(%d,%d,%d)" % (self.x, self.y, self.z)
        return string
        
my_point=Point3D(1,2,3)
print my_point.__repr__()

On the output console, (1 2 3) is printed when I click on the 'Save and Submit Code' button, but it does not let me go to the next level and displays an error message saying that I have not printed (1 2 3).

Please help me people. I am really stuck. Thanks in advance for your help!


#2

Just print the object...

print my_point

#3

Thanks for your reply. I tried it. Again the same thing happens. (1 2 3) is displayed on the output console but I still get the error message which doesn't let me get to the next exercise.

I have one more confusion. Why does printing the object as follows

print my_point

work?


#4

Because we are printing the return value of .__repr__() which is the built in representation of the object, for this purpose.

Did you try to return the formatted string directly?

    return "(%d, %d, %d)" % (self.x, self.y, self.z)

The SCT may be looking for a particular code pattern. Can't say for sure.


#5

It worked! Thank you so much. I reset the code and copied the statements directly from the problem statement. And thank you again for clearing my doubt!


#6

As this courseware is concerned, be diligent to the instructions and only create variables when instructed. Work with the variables you are given and the solution will usually unfold quite seamlessly.


#7

Hi @pvij ,

As @mtf has pointed out, for some of the exercises, Codecademy's submission correctness test (SCT) looks for particular variables in the code. Indeed, in this exercise, it does require you to have a global variable named my_point that is an instance of the class Point3D. However, in this exercise the SCT allows more freedom than that regarding the usage and names of local variables within the Point3D class definition.

The problem with your original code was that the __repr__ method returned this ...

(1,2,3)

... when it should have returned this ...

(1, 2, 3)

Note that there is a difference in spacing within the two different outputs.


#8

Hello @mtf and @appylpye, I will keep your advices in mind in future. Thank you for taking the time to give your suggestions.