Building useful classes! Help please!


#1



Hey @appylpye I have a quick question. this code works. however, i was wondering why it does not work when we replace x, y, z with 1, 2, 3 in the instance of my_point. According to instruction, if x, y, z are the respective numbers, shouldn't they work? Thanks in advance @appylpye

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)   # not working when ('x', 'y', 'z')
print my_point


#2

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

print my_point

#3

The instructions ask for this ...

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

By using the %d format specifier, our __repr__ method can only handle ints.

By doing the following with the %s format specifier, @leonhard.wettengmx.n 's code improves upon the above by enabling the method to handle floats, as well, or any type, for that matter, that has a default string representation ...

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

When we instantiate a Point3D object, the three arguments we specify within the parentheses must all be defined beforehand. So, @orouge , in answer to what I think is your question, unless we have defined x, y, and z outside the class Point3D definition, we cannot do this ...

my_point = Point3D(x, y, z)

#4

Thank you @appylpye and @leonhard.wettengmx.n for clarifying it for me. much Appreciated!


#5

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