class Vector2(object):
    
    def __init__(self, x= 0.0, y = 0.0):
        
        self.x = x
        self.y = y
        
    def __str__(self):
        return "(%s, %s)" % (self.x, self.y)
    
    @classmethod
    def from_points(cls, P1, P2):
        return cls( P2[0] - P1[0], P2[1] - P1[1] )

A = (10.0, 20.0)
B = (30.0, 35.0)

AB = Vector2.from_points(A, B)
print AB

I'M having trouble understanding some of this code. First of all, is the classmethod the same thing as a static method? At what point in this program is it actually called. I also thought I remembered there was another way to right class methods.
What is the parameter cls?
Last but not least, what produces the final output? Is it the line print AB or the __str__ method?

Thanks for any and all replies.

Recommended Answers

All 3 Replies

@staticmethod returns a static method for function.

@classmethod returns a class method for function.

The classmethod is called with the 'cls' argument as first argument and it represents the class.

It's called when you create a class object and will serve as constructor for the class.

At line 13 it will pass the data from the 'from_points()' function to the class.

And when the class object 'AB' is called to be printed the '__str__' function is called.

Hope that helps...

Cheers and Happy coding

If the argument cls is the constructor then I would assume that it is through cls that from_points class methods gets it's x & y arguments from the constructor, being that is what cls represents. But then from_points is called directly via AB = Vector2.from_points(A, B). Which should also call __init__ at that time as well. So does from_points get the x & y values from it parameter cls or from the call in Vectory2.from_points(A, B).
Sorry if slowness, I am somewhat dyslexic.

The from_points function pass the values to the __init__ by the cls variable, and not the other way around.

When you call 'AB = Vector2.from_points(A, B)' it will pass the 'A' and 'B' tuples to the 'from_points' function that will calculate and pass then the result to the class __init__ function.

Cheers and Happy coding

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.