Difference between staticmethod and classmethod

后端 未结 28 2090
一整个雨季
一整个雨季 2020-11-21 06:11

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?

28条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 06:40

    Only the first argument differs:

    • normal method: the current object if automatically passed as an (additional) first argument
    • classmethod: the class of the current object is automatically passed as an (additional) fist argument
    • staticmethod: no extra arguments are automatically passed. What you passed to the function is what you get.

    In more detail...

    normal method

    When an object's method is called, it is automatically given an extra argument self as its first argument. That is, method

    def f(self, x, y)
    

    must be called with 2 arguments. self is automatically passed, and it is the object itself.

    class method

    When the method is decorated

    @classmethod
    def f(cls, x, y)
    

    the automatically provided argument is not self, but the class of self.

    static method

    When the method is decorated

    @staticmethod
    def f(x, y)
    

    the method is not given any automatic argument at all. It is only given the parameters that it is called with.

    usages

    • classmethod is mostly used for alternative constructors.
    • staticmethod does not use the state of the object. It could be a function external to a class. It only put inside the class for grouping functions with similar functionality (for example, like Java's Math class static methods)
    class Point
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        @classmethod
        def frompolar(cls, radius, angle):
            """The `cls` argument is the `Point` class itself"""
            return cls(radius * cos(angle), radius * sin(angle))
    
        @staticmethod
        def angle(x, y):
            """this could be outside the class, but we put it here 
    just because we think it is logically related to the class."""
            return atan(y, x)
    
    
    p1 = Point(3, 2)
    p2 = Point.frompolar(3, pi/4)
    
    angle = Point.angle(3, 2)
    
    

提交回复
热议问题