python-decorators - Python private method - staticmethodとclassmethodの違い

Python class / python / oop / methods

飾ら機能の違いは何ですか @staticmethod と飾ら1 @classmethod

Anand Tripathi



Answer #1
def f(self, x, y)

メソッドが装飾されると

@classmethod
def f(cls, x, y)
@staticmethod
def f(x, y)
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)