Python中的str的静态vs实例方法

8 python string

所以,我已经知道字符串有一个中心方法.

>>> 'a'.center(3)
' a '
Run Code Online (Sandbox Code Playgroud)

然后我注意到我可以使用'str'对象做同样的事情,这是一种类型,因为

>>> type(str)
<type 'type'>
Run Code Online (Sandbox Code Playgroud)

使用这个'type'对象,我可以访问字符串方法,就像它们是静态函数一样.

>>> str.center('a',5)
'  a  '
Run Code Online (Sandbox Code Playgroud)

唉! 这违反了蟒蛇的禅宗.

应该有一个 - 最好只有一个 - 明显的方法来做到这一点.

甚至这两种方法的类型也不同.

>>> type(str.center)
<type 'method_descriptor'>
>>> type('Ni!'.center)
<type 'builtin_function_or_method'>
Run Code Online (Sandbox Code Playgroud)

现在,

  1. 这是一个如何设计python中的类的示例吗?
  2. 为什么类型不同?
  3. 什么是method_descriptor,为什么我要打扰?

谢谢你的回答!

Ric*_*dle 18

这就是Python中的类如何工作:

class C:
    def method(self, arg):
        print "In C.method, with", arg

o = C()
o.method(1)
C.method(o, 1)
# Prints:
# In C.method, with 1
# In C.method, with 1
Run Code Online (Sandbox Code Playgroud)

当你说o.method(1)你可以把它想象成一个简写C.method(o, 1).A method_descriptor是使这项工作成为可能的机器的一部分.

  • 更准确地说,当您访问o.method时,您将获得一个直接绑定到o的包装函数.这是Python最有用的属性之一. (3认同)

lli*_*lib 9

应该有一个 - 最好只有一个 - 明显的方法来做到这一点.

哲学上说,有只有一个明显的方式做到这一点:"a'.center(3).事实上有一种不明显的方式来调用任何方法(即前面的注释器o.method(x)和Type.method(o,x)),这在许多情况下很有用,这一点非常符合与蟒蛇的禅宗.

你的家庭作业是阅读Guido的为什么明确的自我必须留下来.


the*_*edz 5

扩展RichieHindle的答案:

在Python中,类上的所有方法都是惯用的"self"参数.例如:

def method(self, arg): pass
Run Code Online (Sandbox Code Playgroud)

那个"self"参数告诉Python调用该方法的类的实例.在类实例上调用方法时,通常会隐式传递给您:

o.method(1)
Run Code Online (Sandbox Code Playgroud)

但是,您还可以选择使用Object类,并显式传入类实例:

C.method(o, 1)
Run Code Online (Sandbox Code Playgroud)

要使用您的字符串示例,str.center是str对象上的一个方法:

"hi".center(5)
Run Code Online (Sandbox Code Playgroud)

相当于:

str.center("hi", 5)
Run Code Online (Sandbox Code Playgroud)

您正在将str实例"hi"传递给对象,显式执行通常隐含的操作.