파이썬에서 "방법"이란 무엇입니까?
누구든지 Python에서 "메서드"가 무엇인지 아주 간단한 용어로 설명해 주시겠습니까?
초보자를위한 많은 Python 자습서에서이 단어는 초보자가 이미 Python 컨텍스트에서 메서드가 무엇인지 알고있는 것과 같은 방식으로 사용됩니다. 물론이 단어의 일반적인 의미에 대해서는 잘 알고 있지만이 용어가 파이썬에서 무엇을 의미하는지 전혀 모릅니다. 그러니 "Pythonian"방법이 무엇인지 설명해주세요.
아주 간단한 예제 코드는 사진이 천 단어의 가치가 있기 때문에 매우 높이 평가 될 것입니다.
클래스의 멤버 인 함수입니다.
class C:
def my_method(self):
print "I am a C"
c = C()
c.my_method() # Prints "I am a C"
그렇게 간단합니다!
(클래스와 함수 사이의 관계를 제어 할 수있는 몇 가지 대안적인 방법도 있습니다.하지만 질문을 통해 질문이 아니라 기본 사항에 불과하다고 생각합니다.)
메서드는 클래스 인스턴스를 첫 번째 매개 변수로 사용하는 함수입니다. 메서드는 클래스의 멤버입니다.
class C:
def method(self, possibly, other, arguments):
pass # do something here
파이썬에서 구체적으로 무엇을 의미하는지 알고 싶었 기 때문에 바인딩 된 메서드와 바인딩되지 않은 메서드를 구분할 수 있습니다. Python에서 모든 함수 (및 메소드)는 전달되고 "함께 재생할"수있는 객체입니다. 따라서 바인딩되지 않은 메서드와 바인딩 된 메서드의 차이점은 다음과 같습니다.
1) 바인딩 방법
# Create an instance of C and call method()
instance = C()
print instance.method # prints '<bound method C.method of <__main__.C instance at 0x00FC50F8>>'
instance.method(1, 2, 3) # normal method call
f = instance.method
f(1, 2, 3) # method call without using the variable 'instance' explicitly
바인딩 된 메서드는 클래스의 인스턴스에 속하는 메서드입니다. 이 예제에서는 instance.method
라는 인스턴스에 바인딩됩니다 instance
. 바인딩 된 메서드가 호출 될 때마다 인스턴스는 self
규칙에 따라 호출 되는 첫 번째 매개 변수로 자동으로 전달됩니다 .
2) 언 바운드 방법
print C.method # prints '<unbound method C.method>'
instance = C()
C.method(instance, 1, 2, 3) # this call is the same as...
f = C.method
f(instance, 1, 2, 3) # ..this one...
instance.method(1, 2, 3) # and the same as calling the bound method as you would usually do
액세스하면 C.method
(인스턴스 내부가 아닌 클래스 내부의 메서드) 바인딩되지 않은 메서드가 생성됩니다. 호출하려면 메서드가 인스턴스에 바인딩되어 있지 않으므로 인스턴스를 첫 번째 매개 변수로 전달 해야합니다.
그 차이를 알면 메서드를 전달하는 것과 같이 함수 / 메서드를 객체로 사용할 수 있습니다. 예제 사용 사례로 콜백 함수를 정의 할 수 있지만 콜백 함수로 메서드를 제공하려는 API를 상상해보십시오. 문제 없습니다 self.myCallbackMethod
. 콜백으로 전달 하면 인스턴스를 첫 번째 인수로 사용하여 자동으로 호출됩니다. 이것은 C ++와 같은 정적 언어에서는 불가능합니다 (또는 속임수로만 가능).
요점을 얻었기를 바랍니다.) 메소드 기본에 대해 알아야 할 전부라고 생각합니다. classmethod
및 staticmethod
데코레이터 에 대해 더 많이 읽을 수도 있지만 이것은 또 다른 주제입니다.
Python에서 메서드 는 객체의 유형 때문에 주어진 객체에 사용할 수있는 함수입니다 .
당신이 만드는 경우 예를 들어, my_list = [1, 2, 3]
의 append
방법을 적용 할 수 my_list
는 파이썬 목록이기 때문에 : my_list.append(4)
. 모든 목록에는 append
단순히 목록이기 때문에 메서드가 있습니다.
당신이 만드는 경우 또 다른 예로 my_string = 'some lowercase text'
는 upper
방법에 적용 할 수 my_string
는 파이썬 문자열입니다 간단하기 때문에 : my_string.upper()
.
목록에는 upper
메서드가없고 문자열에는 append
메서드 가 없습니다 . 왜? 메소드 는 해당 유형의 객체에 대해 명시 적으로 정의 된 경우에만 특정 객체에 대해 존재하기 때문에 Python 개발자는 (지금까지) 해당 특정 객체에 해당 특정 메소드가 필요하지 않다고 결정했습니다.
메서드를 호출하려면 형식은 object_name.method_name()
이고 메서드에 대한 인수는 괄호 안에 나열됩니다. 메서드는 명명되는 개체에 대해 암시 적으로 작동하므로 개체 자체 가 유일한 필수 인수 이기 때문에 일부 메서드에는 지정된 인수가 없습니다 . 예를 들어 my_string.upper()
에는 나열된 인수가 없습니다. 유일한 필수 인수는 객체 자체이므로 my_string
.
한 가지 일반적인 혼동 포인트는 다음과 같습니다.
import math
math.sqrt(81)
물건 sqrt
의 방법 인가 math
? 아니오. 이것이 모듈 에서 sqrt
함수 를 호출하는 방법 math
입니다. 사용되는 형식은 module_name.function_name()
대신입니다 object_name.method_name()
. 일반적으로, 유일한 방법은 두 가지 형식을 구별하는 (시각적) 코드의 나머지 부분을보고 있는지 인 기간 전에이 ( math
, my_list
, my_string
) 객체 또는 모듈로서 정의된다.
미안하지만, 제 생각에는 RichieHindle이 그 방법을 말하는 것에 대해 완전히 옳습니다.
클래스의 멤버 인 함수입니다.
다음은 클래스의 멤버가되는 함수의 예입니다. 그 이후로 그것은 클래스의 메소드로 작동합니다. 빈 클래스와 하나의 인수가있는 일반 함수 부터 시작해 보겠습니다 .
>>> class C:
... pass
...
>>> def func(self):
... print 'func called'
...
>>> func('whatever')
func called
Now we add a member to the C
class, which is the reference to the function. After that we can create the instance of the class and call its method as if it was defined inside the class:
>>> C.func = func
>>> o = C()
>>> o.func()
func called
We can use also the alternative way of calling the method:
>>> C.func(o)
func called
The o.func
even manifests the same way as the class method:
>>> o.func
<bound method C.func of <__main__.C instance at 0x000000000229ACC8>>
And we can try the reversed approach. Let's define a class and steal its method as a function:
>>> class A:
... def func(self):
... print 'aaa'
...
>>> a = A()
>>> a.func
<bound method A.func of <__main__.A instance at 0x000000000229AD08>>
>>> a.func()
aaa
So far, it looks the same. Now the function stealing:
>>> afunc = A.func
>>> afunc(a)
aaa
The truth is that the method does not accept 'whatever' argument:
>>> afunc('whatever')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method func() must be called with A instance as first
argument (got str instance instead)
IMHO, this is not the argument against method is a function that is a member of a class.
Later found the Alex Martelli's answer that basically says the same. Sorry if you consider it duplication :)
http://docs.python.org/2/tutorial/classes.html#method-objects
Usually, a method is called right after it is bound:
x.f()
In the MyClass example, this will return the string 'hello world'. However, it is not necessary to call a method right away: x.f is a method object, and can be stored away and called at a later time. For example:
xf = x.f while True: print xf()
will continue to print hello world until the end of time.
What exactly happens when a method is called? You may have noticed that x.f() was called without an argument above, even though the function definition for f() specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used...
Actually, you may have guessed the answer: the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.
If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.
If you think of an object as being similar to a noun, then a method is similar to a verb. Use a method right after an object (i.e. a string or a list) to apply a method's action to it.
참고URL : https://stackoverflow.com/questions/3786881/what-is-a-method-in-python
'Nice programing' 카테고리의 다른 글
MySQL. (0) | 2020.11.07 |
---|---|
Core-Data의 사용자 지정 setter 메서드 (0) | 2020.11.07 |
고유 한 값이있는 순열 (0) | 2020.11.07 |
C # 컨트롤러에서 외부 URL로 리디렉션하는 방법 (0) | 2020.11.07 |
jQuery를 사용하여 테이블의 tbody에 행 추가 (0) | 2020.11.07 |