Alex Green Alex Green - 1 month ago 11
C# Question

class vs static methods

I'm new in Python (come from C#), trying to figure out how OOP works here.
Started from very begining I try to implement

Vector
class.
I want to have basis vectors (i, j, k) defined in
Vector
class.
In C#, I can do this like that:

public class Vector
{
// fields...
public Vector(int[] array){
//...
}

public static Vector i(){
return new Vector(new int[1, 0, 0]);
}
}


Exploring Python I found 2 ways how to implement this: using either
@classmethod
or
@staticmethod
:

class Vector:
def __init__(array):
#...

@classmethod
def i(self):
return Vector([1, 0, 0])


Since I don't need to have access to any information inside the class, should I really use
@classmethod
?

Answer Source

I think you've confused yourself with your naming of arguments a bit. The first argument a class method receives is the class itself, which would be Vector, for now, until you have a subclass. A class method would be implemented like this:

    @classmethod
    def i(cls):
        return cls([1, 0, 0])

Generally, an instance method (no decorator) calls its first argument self, which is the instance. A class method has cls, which is the class, which can be used to construct an instance. A static method takes no "extra" argument, so your other option, if you want to always return a Vector, is:

    @staticmethod
    def i():
        return Vector([1, 0, 0])