Python 中的“方法”是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3786881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a "method" in Python?
提问by brilliant
Can anyone, please, explain to me in very simple terms what a "method" is in Python?
任何人都可以用非常简单的术语向我解释 Python 中的“方法”是什么?
The thing is in many Python tutorials for beginners this word is used in such way as if the beginner already knew what a method is in the context of Python. While I am of course familiar with the general meaning of this word, I have no clue what this term means in Python. So, please, explain to me what the "Pythonian" method is all about.
在许多面向初学者的 Python 教程中,这个词的使用方式好像初学者已经知道 Python 上下文中的方法是什么。虽然我当然熟悉这个词的一般含义,但我不知道这个词在 Python 中的含义。所以,请向我解释什么是“Pythonian”方法。
Some very simple example code would be very much appreciated as a picture is worth thousand words.
一些非常简单的示例代码将非常受欢迎,因为一张图片价值一千字。
采纳答案by RichieHindle
It's a function which is a member of a class:
这是一个函数,它是一个类的成员:
class C:
def my_method(self):
print "I am a C"
c = C()
c.my_method() # Prints "I am a C"
Simple as that!
就那么简单!
(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)
(还有一些替代方法,允许您控制类和函数之间的关系。但我从您的问题中猜测您不是在问那个,而只是基础知识。)
回答by AndiDog
A method is a function that takes a class instance as its first parameter. Methods are members of classes.
方法是将类实例作为其第一个参数的函数。方法是类的成员。
class C:
def method(self, possibly, other, arguments):
pass # do something here
As you wanted to know what it specifically means in Python, one can distinguish between bound and unbound methods. In Python, all functions (and as such also methods) are objects which can be passed around and "played with". So the difference between unbound and bound methods is:
由于您想知道它在 Python 中的具体含义,因此可以区分绑定方法和未绑定方法。在 Python 中,所有函数(以及方法)都是可以传递和“玩弄”的对象。所以 unbound 和 bound 方法的区别是:
1) Bound methods
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
Bound methods are methods that belong to instances of a class. In this example, instance.methodis bound to the instance called instance. Everytime that bound method is called, the instance is passed as first parameter automagically - which is called selfby convention.
绑定方法是属于类实例的方法。在本例中,instance.method绑定到名为 的实例instance。每次调用绑定方法时,实例都会自动作为第一个参数传递 -self按照约定调用。
2) Unbound methods
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
When you access C.method(the method inside a class instead of inside an instance), you get an unbound method. If you want to call it, you have to pass the instance as first parameter because the method is notbound to any instance.
当您访问C.method(类内部的方法而不是实例内部的方法)时,您将获得一个未绑定的方法。如果要调用它,则必须将实例作为第一个参数传递,因为该方法未绑定到任何实例。
Knowing that difference, you can make use of functions/methods as objects, like passing methods around. As an example use case, imagine an API that lets you define a callback function, but you want to provide a method as callback function. No problem, just pass self.myCallbackMethodas the callback and it will automatically be called with the instance as first argument. This wouldn't be possible in static languages like C++ (or only with trickery).
知道这种区别后,您可以将函数/方法用作对象,就像传递方法一样。作为示例用例,假设一个 API 允许您定义回调函数,但您希望提供一个方法作为回调函数。没问题,只需self.myCallbackMethod作为回调传递,它将自动以实例作为第一个参数调用。这在像 C++ 这样的静态语言中是不可能的(或者只有使用技巧)。
Hope you got the point ;) I think that is all you should know about method basics. You could also read more about the classmethodand staticmethoddecorators, but that's another topic.
希望你明白了;) 我认为这就是你应该了解的方法基础知识。您还可以阅读更多关于classmethod和staticmethod装饰器的信息,但这是另一个主题。
回答by pepr
Sorry, but--in my opinion--RichieHindle is completely right about saying that method...
抱歉,但是——在我看来——RichieHindle 说这种方法是完全正确的......
It's a function which is a member of a class.
它是一个函数,它是类的成员。
Here is the example of a function that becomes the member of the class. Since then it behaves as a method of the class. Let's start with the emptyclass and the normal function with one argument:
这是成为类成员的函数的示例。从那时起,它就表现为类的方法。让我们从空类和带一个参数的普通函数开始:
>>> class C:
... pass
...
>>> def func(self):
... print 'func called'
...
>>> func('whatever')
func called
Now we add a member to the Cclass, 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类添加一个成员,它是对函数的引用。之后我们可以创建类的实例并调用它的方法,就好像它是在类中定义的一样:
>>> 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.funceven manifests the same way as the class method:
该o.func甚至体现方式相同类方法:
>>> 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.
恕我直言,这不是反对method is a function that is a member的论点。
Later foundthe Alex Martelli's answerthat basically says the same. Sorry if you consider it duplication :)
后来发现了亚历马尔泰利的答案,基本上也是这么说的。对不起,如果你认为它是重复的:)
回答by acmerfight
http://docs.python.org/2/tutorial/classes.html#method-objects
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.
通常,方法在绑定后立即调用:
x.f()在 MyClass 示例中,这将返回字符串“hello world”。但是,没有必要立即调用方法:xf 是一个方法对象,可以存储起来并在以后调用。例如:
xf = x.f while True: print xf()将继续打印 hello world 直到时间结束。
当一个方法被调用时到底发生了什么?您可能已经注意到,即使 f() 的函数定义指定了一个参数,在调用 xf() 时也不带参数。争论怎么了?当一个需要参数的函数在没有任何参数的情况下被调用时,Python 肯定会引发异常——即使该参数实际上没有被使用......
实际上,您可能已经猜到了答案:方法的特殊之处在于将对象作为函数的第一个参数传递。在我们的示例中,调用 xf() 完全等同于 MyClass.f(x)。通常,调用带有 n 个参数列表的方法等效于调用带有参数列表的相应函数,该参数列表是通过在第一个参数之前插入方法的对象而创建的。
如果您仍然不了解方法的工作原理,那么查看实现也许可以澄清问题。当引用的实例属性不是数据属性时,将搜索其类。如果名称表示作为函数对象的有效类属性,则通过打包(指向)实例对象和刚刚在抽象对象中一起找到的函数对象来创建方法对象:这就是方法对象。当使用参数列表调用方法对象时,会根据实例对象和参数列表构造一个新的参数列表,并使用这个新的参数列表调用函数对象。
回答by Kevin Markham
In Python, a methodis a function that is available for a given object because of the object's type.
在 Python 中,方法是由于对象的类型而可用于给定对象的函数。
For example, if you create my_list = [1, 2, 3], the appendmethod can be applied to my_listbecause it's a Python list: my_list.append(4). All lists have an appendmethod simply because they are lists.
例如,如果您 create my_list = [1, 2, 3],则append可以应用该方法,my_list因为它是一个 Python 列表:my_list.append(4)。所有列表都有一个append方法,因为它们是列表。
As another example, if you create my_string = 'some lowercase text', the uppermethod can be applied to my_stringsimply because it's a Python string: my_string.upper().
再举一个例子,如果你 create my_string = 'some lowercase text',该upper方法可以应用到my_string仅仅因为它是一个 Python 字符串:my_string.upper()。
Lists don't have an uppermethod, and strings don't have an appendmethod. Why? Because methods only exist for a particular object if they have been explicitly defined for that type of object, and Python's developers have (so far) decided that those particular methods are not needed for those particular objects.
列表没有upper方法,字符串也没有append方法。为什么?因为方法只存在于特定对象,如果它们已为该类型的对象显式定义,并且 Python 的开发人员(到目前为止)已经决定那些特定对象不需要这些特定方法。
To call a method, the format is object_name.method_name(), and any arguments to the method are listed within the parentheses. The method implicitly acts on the object being named, and thus some methods don't have any stated arguments since the object itselfis the only necessary argument. For example, my_string.upper()doesn't have any listed arguments because the only required argument is the object itself, my_string.
要调用一个方法,格式为object_name.method_name(),并且该方法的任何参数都列在括号内。该方法隐式地作用于被命名的对象,因此一些方法没有任何声明的参数,因为对象本身是唯一必要的参数。例如,my_string.upper()没有任何列出的参数,因为唯一需要的参数是对象本身,my_string。
One common point of confusion regards the following:
一个常见的混淆点如下:
import math
math.sqrt(81)
Is sqrta method of the mathobject? No.This is how you call the sqrtfunction from the mathmodule. The format being used is module_name.function_name(), instead of object_name.method_name(). In general, the only way to distinguish between the two formats (visually) is to look in the rest of the code and see if the part before the period(math, my_list, my_string) is defined as an object or a module.
是对象sqrt的方法math吗?不。这就是您sqrt从math模块调用函数的方式。使用的格式是module_name.function_name(), 而不是object_name.method_name()。一般来说,区分这两种格式(视觉上)的唯一方法是查看代码的其余部分,看看句点( math, my_list, my_string)之前的部分是定义为对象还是模块。
回答by Malik Singleton
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.
如果您认为对象类似于名词,那么方法类似于动词。在对象(即字符串或列表)之后立即使用方法将方法的操作应用于它。
回答by Christian Kunert
To understand methods you must first think in terms of object oriented programming: Let's take a car as a a class. All cars have things in common and things that make them unique, for example all cars have 4 wheels, doors, a steering wheel.... but Your individual car (Lets call it, my_toyota) is red, goes from 0-60 in 5.6s Further the car is currently located at my house, the doors are locked, the trunk is empty... All those are properties of the instance of my_toyota. your_honda might be on the road, trunk full of groceries ...
要理解方法,您必须首先从面向对象编程的角度进行思考:让我们将汽车视为一个类。所有汽车都有共同点和独特之处,例如所有汽车都有 4 个轮子、车门、一个方向盘……但是您的个人汽车(我们称之为 my_toyota)是红色的,从 0 到 60 5.6s 此外,汽车目前位于我家,车门已锁,后备箱是空的……所有这些都是 my_toyota 实例的属性。your_honda 可能在路上,行李箱里装满了杂货......
However there are things you can do with the car. You can drive it, you can open the door, you can load it. Those things you can do with a car are methods of the car, and they change a properties of the specific instance.
但是,您可以使用汽车做一些事情。你可以驾驶它,你可以打开门,你可以装载它。你可以用汽车做的那些事情是汽车的方法,它们改变了特定实例的属性。
as pseudo code you would do:
作为伪代码,你会这样做:
my_toyota.drive(shop)
to change the location from my home to the shop or
将位置从我家更改为商店或
my_toyota.load([milk, butter, bread]
by this the trunk is now loaded with [milk, butter, bread].
至此,后备箱里装满了[牛奶、黄油、面包]。
As such a method is practically a function that acts as part of the object:
因此,方法实际上是作为对象一部分的函数:
class Car(vehicle)
n_wheels = 4
load(self, stuff):
'''this is a method, to load stuff into the trunk of the car'''
self.open_trunk
self.trunk.append(stuff)
self.close_trunk
the code then would be:
然后代码将是:
my_toyota = Car(red)
my_shopping = [milk, butter, bread]
my_toyota.load(my_shopping)

