programing

Python에서 메서드를 매개 변수로 전달하려면 어떻게 해야 합니까?

sourcetip 2022. 10. 18. 22:45
반응형

Python에서 메서드를 매개 변수로 전달하려면 어떻게 해야 합니까?

메서드를 메서드에 파라미터로 전달할 수 있습니까?

self.method2(self.method1)

def method1(self):
    return 'hello world'

def method2(self, methodToRun):
    result = methodToRun.call()
    return result

네, 그렇습니다, 작성하신 대로 방법 이름만 사용하시면 됩니다.메서드와 함수는 다른 모든 것과 마찬가지로 Python의 객체이며 변수를 수행하는 방법으로 전달할 수 있습니다.실제로 메서드(또는 함수)를 실제 호출 가능한 코드 객체의 값이 되는 변수로 생각할 수 있습니다.

메서드에 대해 질문하셨기 때문에 다음 예에서는 메서드를 사용하고 있습니다만, 아래의 모든 것은 함수에 동일하게 적용됩니다(단, 이 예에서는 제외).self파라미터)를 참조해 주세요.

전달된 메서드 또는 함수를 호출하려면 메서드(또는 함수)의 정규 이름을 사용하는 것과 동일한 방법으로 바인딩된 이름을 사용합니다.

def method1(self):
    return 'hello world'

def method2(self, methodToRun):
    result = methodToRun()
    return result

obj.method2(obj.method1)

주의: 제 생각에는__call__()방법은 존재합니다. 즉, 기술적으로 할 수 있습니다.methodToRun.__call__()단, 절대 명시적으로 해서는 안 됩니다. __call__()는 실장하는 것으로, 자신의 코드에서 기동하는 것이 아닙니다.

원하신다면method1그러면 일이 좀 더 복잡해져요 method2에 인수를 전달하는 방법에 대한 약간의 정보를 기재해야 합니다.method1어디서부터 이러한 주장에 대한 값을 얻어야 합니다.예를 들어, 만약method1는 다음 한 가지 인수를 채택해야 합니다.

def method1(self, spam):
    return 'hello ' + str(spam)

그러면 너는 쓸 수 있다.method2전달되는 인수 1개를 사용하여 호출합니다.

def method2(self, methodToRun, spam_value):
    return methodToRun(spam_value)

또는 스스로 계산한다는 인수를 사용하여 다음과 같이 처리한다.

def method2(self, methodToRun):
    spam_value = compute_some_value()
    return methodToRun(spam_value)

이를 전달된 값과 계산된 값의 다른 조합으로 확장할 수 있습니다.

def method1(self, spam, ham):
    return 'hello ' + str(spam) + ' and ' + str(ham)

def method2(self, methodToRun, ham_value):
    spam_value = compute_some_value()
    return methodToRun(spam_value, ham_value)

또는 키워드 인수를 사용해도

def method2(self, methodToRun, ham_value):
    spam_value = compute_some_value()
    return methodToRun(spam_value, ham=ham_value)

모르면 쓸 때method2, 어떤 인수methodToRun는 인수 언팩을 사용하여 일반적인 방법으로 호출할 수도 있습니다.

def method1(self, spam, ham):
    return 'hello ' + str(spam) + ' and ' + str(ham)

def method2(self, methodToRun, positional_arguments, keyword_arguments):
    return methodToRun(*positional_arguments, **keyword_arguments)

obj.method2(obj.method1, ['spam'], {'ham': 'ham'})

이 경우positional_arguments리스트 또는 태플 또는 유사한 것이어야 합니다.keyword_argumentsdict 또는 유사합니다.method2변경할 수 있습니다.positional_arguments그리고.keyword_arguments(예를 들어 특정 인수를 추가 또는 삭제하거나 값을 변경하는 경우)를 호출하기 전에method1.

네, 가능합니다.그냥 이렇게 부르세요.

class Foo(object):
    def method1(self):
        pass
    def method2(self, method):
        return method()

foo = Foo()
foo.method2(foo.method1)

스탠드아론의 작업 예를 표시하기 위해 다시 작성한 예를 다음에 나타냅니다.

class Test:
    def method1(self):
        return 'hello world'

    def method2(self, methodToRun):
        result = methodToRun()
        return result

    def method3(self):
        return self.method2(self.method1)

test = Test()

print test.method3()

를 사용하다lambda기능.
그래서 당신이 논쟁을 하지 않는다면, 모든 것이 매우 하찮아진다.

def method1():
    return 'hello world'

def method2(methodToRun):
    result = methodToRun()
    return result

method2(method1)

단, 에 1개(또는 여러 개)의 인수가 있다고 합시다.method1:

def method1(param):
    return 'hello ' + str(param)

def method2(methodToRun):
    result = methodToRun()
    return result

그러면 간단히 호출할 수 있습니다.method2~하듯이method2(lambda: method1('world')).

method2(lambda: method1('world'))
>>> hello world
method2(lambda: method1('reader'))
>>> hello reader

나는 이것이 여기에 언급된 다른 대답들보다 훨씬 더 깨끗하다고 생각한다.

클래스의 메서드를 인수로 전달하고 싶지만 아직 호출할 객체가 없는 경우 첫 번째 인수(즉, "self" 인수)로 지정한 객체를 전달하기만 하면 됩니다.

class FooBar:

    def __init__(self, prefix):
        self.prefix = prefix

    def foo(self, name):
        print "%s %s" % (self.prefix, name)


def bar(some_method):
    foobar = FooBar("Hello")
    some_method(foobar, "World")

bar(FooBar.foo)

그러면 "Hello World"가 인쇄됩니다.

예. 함수(및 메서드)는 Python의 퍼스트 클래스 객체입니다.다음과 같은 기능이 있습니다.

def foo(f):
    print "Running parameter f()."
    f()

def bar():
    print "In bar()."

foo(bar)

출력:

Running parameter f().
In bar().

이러한 종류의 질문은 Python 인터프리터 또는 더 많은 기능을 위해 IPython 쉘을 사용하여 대답하는 것은 간단합니다.

서른그래서 당신은 그것들을 돌려서 목록과 받아쓰기에 저장할 수 있고, 원하는 것을 할 수 있습니다.할 수 있는 에 호출할 수 입니다.__call__그 위에 올려놔요. __call__ 인수 에 이 메서드를 호출하면 .methodToRun().

원하는 것은 아니지만, 관련된 유용한 툴은getattr()이치노

class MyClass:
   def __init__(self):
      pass
   def MyMethod(self):
      print("Method ran")

# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now

# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()

예: 단순한 함수 호출 래퍼:

def measure_cpu_time(f, *args):
    t_start = time.process_time()
    ret = f(*args)
    t_end = time.process_time()
    return t_end - t_start, ret

언급URL : https://stackoverflow.com/questions/706721/how-do-i-pass-a-method-as-a-parameter-in-python

반응형