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.

Dani AI

Generated

A few precise clarifications that build on 's answer and target the exact questions had.

A classmethod is a normal function that Python wraps so the class object is supplied automatically as the first argument; a staticmethod gets no implicit argument at all. Classmethods are commonly used as alternate constructors because they can call cls(...) to create an instance and they respect subclassing (calling the method on a subclass returns an instance of that subclass). For example:

class Base(object):
    def __init__(self, v): self.v = v

    @classmethod
    def make(cls, v):
        return cls(v)

class Sub(Base): pass

print(Base.make(1).__class__.__name__)   # Base
print(Sub.make(2).__class__.__name__)    # Sub

You can also bind a classmethod without the decorator by assigning MyClass.method = classmethod(function) — that is the older explicit form.

When Vector2.from_points(A, B) runs, the function body executes with the class object available (commonly named cls) and the two point arguments. If from_points calls cls(x, y), Python constructs the new object by invoking __new__ and then __init__ on it — that is the standard creation sequence for instances. See the data model section on object construction for details: object.new and construction behavior.

As for printing: the print operation (or str() around the object) uses __str__ if present; the interactive interpreter falls back to __repr__. If __str__ is not defined, Python will use __repr__. See the docs on __repr__/__str__: object.repr and string representations.

Quick tips: in Python 2 inherit from object so you have new-style behavior; when debugging, compare str(obj) vs repr(obj); and consider collections.namedtuple or dataclasses (Python 3.7+) for simple immutable vector-like types.

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.