programing

Python의 정적 메서드?

firstcheck 2022. 12. 27. 21:26
반응형

Python의 정적 메서드?

클래스 인스턴스에서 직접 호출할 수 있는 정적 메서드를 정의할 수 있습니까?

MyClass.the_static_method()

네, 데코레이터 사용:

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print(x)

MyClass.the_static_method(2)  # outputs 2

에는 스태틱 되고 있는 .staticmethod코레데이것은, Python 의 낡은 버전(2.2 및 2.3)을 서포트할 필요가 있는 경우에만 사용할 수 있습니다.

class MyClass(object):
    def the_static_method(x):
        print(x)
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2)  # outputs 2

은 첫 예시와 (사용법).@staticmethod는, 멋진 구문을 하지 않는 것 는 멋진 데코레이터 구문을 사용하지 않을 뿐입니다.

마지막으로, 적게 사용하세요!Python에서 static-method가 필요한 상황은 거의 없으며, 별도의 "최상위" 기능이 더 명확해졌을 때 여러 번 사용하는 것을 보았습니다.


다음은 매뉴얼에서 발췌한 것입니다.

스태틱 메서드는 암묵적인 첫 번째 인수를 수신하지 않습니다.스태틱 방식을 선언하려면 다음 관용구를 사용합니다.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@staticmethod 형식은 함수 데코레이터입니다.자세한 내용은 함수 정의의 함수 정의에 대한 설명을 참조하십시오.

에서 호출할 수 클래스에서는 할 수 있습니다).C.f()등에C().f()클래스를 제외하고 인스턴스는 무시됩니다.

Python의 정적 메서드는 Java 또는 C++와 유사합니다.보다 고도의 개념에 대해서는, 을 참조해 주세요.

정적 방법에 대한 자세한 내용은 표준 유형 계층의 표준 유형 계층에 대한 설명서를 참조하십시오.

버전 2.2의 새로운 기능

버전 2.4에서 변경: 함수 데코레이터 구문이 추가되었습니다.

난 스티븐이 사실 맞는 것 같아.첫 번째 질문에 답하려면 클래스 메서드를 설정하기 위해 첫 번째 인수가 호출 인스턴스가 아니라고 가정하고 클래스에서 메서드만 호출하도록 합니다.

이3.하고 있습니다).2.Python 2.x를 사용할 수 .TypeError클래스 자체에서 메서드를 호출합니다.)

예를 들어 다음과 같습니다.

class Dog:
    count = 0 # this is a class variable
    dogs = [] # this is a class variable

    def __init__(self, name):
        self.name = name #self.name is an instance variable
        Dog.count += 1
        Dog.dogs.append(name)

    def bark(self, n): # this is an instance method
        print("{} says: {}".format(self.name, "woof! " * n))

    def rollCall(n): #this is implicitly a class method (see comments below)
        print("There are {} dogs.".format(Dog.count))
        if n >= len(Dog.dogs) or n < 0:
            print("They are:")
            for dog in Dog.dogs:
                print("  {}".format(dog))
        else:
            print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))

fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)

이 코드에서는 "rollCall" 메서드는 첫 번째 인수가 인스턴스가 아니라고 가정합니다(클래스가 아닌 인스턴스에서 호출된 경우).인스턴스가 아닌 클래스에서 "rollCall"이 호출되는 한 코드는 정상적으로 작동합니다.인스턴스에서 "rollCall"을 호출하려고 하면 다음과 같이 됩니다.

rex.rollCall(-1)

단, 2개의 인수(자신과 -1)가 송신되기 때문에 예외가 발생합니다.또, 「rollCall」은 1개의 인수만을 받아들이도록 정의되어 있습니다.

덧붙여서, rex.rollCall()은 올바른 수의 인수를 전송하지만 함수가 n을 수치로 예상할 때 n이 Dog 인스턴스(즉, rex)를 나타내기 때문에 예외가 발생합니다.

여기서 장식이 필요합니다.예를 들어, 「roll Call」메서드에 앞서,

@staticmethod

그 후 메서드가 스태틱하다고 명시적으로 기술함으로써 인스턴스에서 호출할 수도 있습니다.지금이다,

rex.rollCall(-1)

효과가 있을 거야메서드 정의 앞에 @staticmethod를 삽입하면 인스턴스가 인수로서 자신을 송신할 수 없게 됩니다.

이것을 확인하려면 , @static method 행에 코멘트 아웃을 가하거나 하지 않고, 다음의 코드를 시험합니다.

class Dog:
    count = 0 # this is a class variable
    dogs = [] # this is a class variable

    def __init__(self, name):
        self.name = name #self.name is an instance variable
        Dog.count += 1
        Dog.dogs.append(name)

    def bark(self, n): # this is an instance method
        print("{} says: {}".format(self.name, "woof! " * n))

    @staticmethod
    def rollCall(n):
        print("There are {} dogs.".format(Dog.count))
        if n >= len(Dog.dogs) or n < 0:
            print("They are:")
            for dog in Dog.dogs:
                print("  {}".format(dog))
        else:
            print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))


fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
rex.rollCall(-1)

네, 스태틱 메서드 데코레이터를 확인해 주세요.

>>> class C:
...     @staticmethod
...     def hello():
...             print "Hello World"
...
>>> C.hello()
Hello World

이렇게 쓸 @staticmethod가 필요 하고 클래스에서 합니다.(셀프 파라미터가 필요 없는) 메서드를 선언하고 클래스에서 호출합니다.에라도 부를 수 않은)에만.

대부분 기능만 쓰시는데...

Python의 정적 메서드?

Python에서 다음과 같은 정적 메서드를 사용하여 클래스를 초기화하지 않고 호출할 수 있습니까?

ClassName.StaticMethod()

네, 정적 메서드는 다음과 같이 만들 수 있습니다(단, 메서드에 CamelCase 대신 밑줄을 사용하는 것이 좀 Phythonic하지만).

class ClassName(object):

    @staticmethod
    def static_method(kwarg1=None):
        '''return a value that is a function of kwarg1'''

위에서는 데코레이터 구문을 사용합니다.이 구문은 다음과 같습니다.

class ClassName(object):

    def static_method(kwarg1=None):
        '''return a value that is a function of kwarg1'''

    static_method = staticmethod(static_method)

이것은, 설명한 대로 사용할 수 있습니다.

ClassName.static_method()

스태틱 방식의 빌트인 예는 다음과 같습니다.str.maketrans()Python 3의 3의 .stringPython 2 python python 。


할 수 또 하나의 으로는 '비슷하다'가.classmethod차이점은 classmethod는 클래스를 암묵적인 첫 번째 인수로 취득하고 서브클래스를 암묵적인 첫 번째 인수로 취득하는 것입니다.

class ClassName(object):

    @classmethod
    def class_method(cls, kwarg1=None):
        '''return a value that is a function of the class and kwarg1'''

:cls첫 번째 인수에 필요한 이름은 아니지만, 대부분의 경험이 풍부한 Python 코더는 다른 것을 사용하면 제대로 처리되지 않은 것으로 간주합니다.

이들은 일반적으로 대체 생성자로 사용됩니다.

new_instance = ClassName.class_method()

기본 제공 예는 다음과 같습니다.dict.fromkeys():

new_dict = dict.fromkeys(['key1', 'key2'])

가장 간단한 방법은 이러한 기능을 클래스 밖에 두는 것입니다.

class Dog(object):
    def __init__(self, name):
        self.name = name

    def bark(self):
        if self.name == "Doggy":
            return barking_sound()
        else:
            return "yip yip"

def barking_sound():
    return "woof woof"

이 방법을 사용하면 내부 객체 상태를 수정하거나 사용하는 기능(부작용이 있음)을 클래스에 유지할 수 있고 재사용 가능한 유틸리티 기능을 외부로 이동할 수 있습니다.

이 파일의 이름은dogs.py이걸 쓰려면dogs.barking_sound()대신dogs.Dog.barking_sound.

클래스의 일부로 정적 메서드가 필요한 경우 정적 메서드 데코레이터를 사용할 수 있습니다.

정적 메서드 객체의 동작의 특수성 외에도 모듈레벨 코드를 정리할 때 어떤 장점이 있습니다.

# garden.py
def trim(a):
    pass

def strip(a):
    pass

def bunch(a, b):
    pass

def _foo(foo):
    pass

class powertools(object):
    """
    Provides much regarded gardening power tools.
    """
    @staticmethod
    def answer_to_the_ultimate_question_of_life_the_universe_and_everything():
        return 42

    @staticmethod
    def random():
        return 13

    @staticmethod
    def promise():
        return True

def _bar(baz, quux):
    pass

class _Dice(object):
    pass

class _6d(_Dice):
    pass

class _12d(_Dice):
    pass

class _Smarter:
    pass

class _MagicalPonies:
    pass

class _Samurai:
    pass

class Foo(_6d, _Samurai):
    pass

class Bar(_12d, _Smarter, _MagicalPonies):
    pass

...

# tests.py
import unittest
import garden

class GardenTests(unittest.TestCase):
    pass

class PowertoolsTests(unittest.TestCase):
    pass

class FooTests(unittest.TestCase):
    pass

class BarTests(unittest.TestCase):
    pass

...

# interactive.py
from garden import trim, bunch, Foo

f = trim(Foo())
bunch(f, Foo())

...

# my_garden.py
import garden
from garden import powertools

class _Cowboy(garden._Samurai):
    def hit():
        return powertools.promise() and powertools.random() or 0

class Foo(_Cowboy, garden.Foo):
    pass

이제 특정 컴포넌트를 사용해야 하는 컨텍스트에서 좀 더 직관적이고 자기 문서화되어 개별 테스트 케이스를 명명하는 데 이상적일 뿐만 아니라 테스트 모듈이 퓨리스트 테스트 대상 실제 모듈에 어떻게 매핑되는지에 대한 간단한 접근 방식을 제공합니다.

프로젝트의 유틸리티 코드를 정리할 때 이 방법을 적용할 수 있는 경우가 자주 있습니다.꽤 자주, 사람들은 즉시 달려들어서utils패키징 후 9개의 모듈로 끝납니다.하나는 120 LOC이고 나머지는 기껏해야 24 LOC입니다.나는 이것부터 시작해서 그것을 패키지로 변환하고 진정으로 자격이 있는 야수만을 위한 모듈을 만드는 것을 선호한다.

# utils.py
class socket(object):
    @staticmethod
    def check_if_port_available(port):
        pass

    @staticmethod
    def get_free_port(port)
        pass

class image(object):
    @staticmethod
    def to_rgb(image):
        pass

    @staticmethod
    def to_cmyk(image):
        pass

따라서 정적 메서드는 클래스의 개체를 만들지 않고 호출할 수 있는 메서드입니다.예:-

    @staticmethod
    def add(a, b):
        return a + b

b = A.add(12,12)
print b

위의 예에서는add클래스 이름으로 호출됩니다.A오브젝트명이아닙니다.

다른 사람의 답변을 요약하고 추가함으로써 파이썬에서 정적 메서드 또는 변수를 선언하는 방법은 여러 가지가 있습니다.

  1. static method()를 데코레이터로 사용하는 경우:정적인 방법으로 선언된 방법(기능) 위에 장식기를 올려놓기만 하면 된다.예를 들면.
class Calculator:
    @staticmethod
    def multiply(n1, n2, *args):
        Res = 1
        for num in args: Res *= num
        return n1 * n2 * Res

print(Calculator.multiply(1, 2, 3, 4))              # 24
  1. 파라미터 함수로 static method()를 사용하는 경우:이 메서드는 함수 유형의 인수를 수신할 수 있으며 전달된 함수의 정적 버전을 반환합니다.예를 들면.
class Calculator:
    def add(n1, n2, *args):
        return n1 + n2 + sum(args)

Calculator.add = staticmethod(Calculator.add)
print(Calculator.add(1, 2, 3, 4))                   # 10
  1. classmethod()를 데코레이터로 사용하는 경우: @classmethod는 함수에 대해 @staticmethod와 유사한 영향을 미치지만, 이번에는 함수에서 추가 인수를 수용해야 합니다(인스턴스 변수의 self 파라미터와 유사).예를 들면.
class Calculator:
    num = 0
    def __init__(self, digits) -> None:
        Calculator.num = int(''.join(digits))

    @classmethod
    def get_digits(cls, num):
        digits = list(str(num))
        calc = cls(digits)
        return calc.num

print(Calculator.get_digits(314159))                # 314159
  1. classmethod()를 파라미터 함수로 사용: @classmethod는 클래스 정의를 변경하지 않을 경우 파라미터 함수로도 사용할 수 있습니다.예를 들면.
class Calculator:
    def divide(cls, n1, n2, *args):
        Res = 1
        for num in args: Res *= num
        return n1 / n2 / Res

Calculator.divide = classmethod(Calculator.divide)

print(Calculator.divide(15, 3, 5))                  # 1.0
  1. 직접 선언 - 다른 모든 메서드 외부에서 선언된 메서드/변수는 클래스 내에서 자동으로 정적입니다.
class Calculator:   
    def subtract(n1, n2, *args):
        return n1 - n2 - sum(args)

print(Calculator.subtract(10, 2, 3, 4))             # 1

전체

class Calculator:
    num = 0
    def __init__(self, digits) -> None:
        Calculator.num = int(''.join(digits))
    
    
    @staticmethod
    def multiply(n1, n2, *args):
        Res = 1
        for num in args: Res *= num
        return n1 * n2 * Res


    def add(n1, n2, *args):
        return n1 + n2 + sum(args)
    

    @classmethod
    def get_digits(cls, num):
        digits = list(str(num))
        calc = cls(digits)
        return calc.num


    def divide(cls, n1, n2, *args):
        Res = 1
        for num in args: Res *= num
        return n1 / n2 / Res


    def subtract(n1, n2, *args):
        return n1 - n2 - sum(args)
    



Calculator.add = staticmethod(Calculator.add)
Calculator.divide = classmethod(Calculator.divide)

print(Calculator.multiply(1, 2, 3, 4))              # 24
print(Calculator.add(1, 2, 3, 4))                   # 10
print(Calculator.get_digits(314159))                # 314159
print(Calculator.divide(15, 3, 5))                  # 1.0
print(Calculator.subtract(10, 2, 3, 4))             # 1

파이썬에서 OOP를 마스터하려면 Python 문서를 참조하십시오.

Python Static 메서드는 두 가지 방법으로 만들 수 있습니다.

  1. static method() 사용

    class Arithmetic:
        def add(x, y):
            return x + y
    # create add static method
    Arithmetic.add = staticmethod(Arithmetic.add)
    
    print('Result:', Arithmetic.add(15, 10))
    

출력:

결과: 25

  1. @static method 사용

    class Arithmetic:
    
    # create add static method
    @staticmethod
    def add(x, y):
        return x + y
    
    print('Result:', Arithmetic.add(15, 10))
    

출력:

결과: 25

나는 가끔 이 질문을 받는다.마음에 드는 사용 사례와 예는 다음과 같습니다.

jeffs@jeffs-desktop:/home/jeffs  $ python36
Python 3.6.1 (default, Sep  7 2017, 16:36:03) 
[GCC 6.3.0 20170406] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cmath
>>> print(cmath.sqrt(-4))
2j
>>>
>>> dir(cmath)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
>>> 

cmath 오브젝트에는 상태가 없기 때문에 class cmath 오브젝트를 작성하는 것은 의미가 없습니다.단, cmath는 모두 어떤 식으로든 관련된 메서드의 집합입니다.위의 예에서는 cmath의 모든 함수는 어떤 식으로든 복소수에 의해 동작합니다.

언급URL : https://stackoverflow.com/questions/735975/static-methods-in-python

반응형