Python 中 str 的静态与实例方法 [英] Static vs instance methods of str in Python

查看:23
本文介绍了Python 中 str 的静态与实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我了解到字符串有一个中心方法.

<预><代码>>>>'a'.center(3)' 一种 '

然后我注意到我可以使用作为类型的str"对象来做同样的事情,因为

<预><代码>>>>类型(字符串)<输入'类型'>

使用这个类型"对象,我可以像访问静态函数一样访问字符串方法.

<预><代码>>>>str.center('a',5)' 一种 '

唉!这违反了python的禅宗.

应该有一种——最好只有一种——显而易见的方法.

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

<预><代码>>>>类型(str.center)<输入'method_descriptor'>>>>type('Ni!'.center)<输入'builtin_function_or_method'>

现在

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

感谢您的回答!

解决方案

Python 中的类就是这样工作的:

C 类:定义方法(自我,arg):打印在 C.method 中,与",argo = C()o.方法(1)C.方法(o, 1)# 印刷:# 在 C.method 中,使用 1# 在 C.method 中,使用 1

当您说 o.method(1) 时,您可以将其视为 C.method(o, 1) 的简写.method_descriptor 是实现这一目标的机制的一部分.

So, I have learnt that strings have a center method.

>>> 'a'.center(3)
' a '

Then I have noticed that I can do the same thing using the 'str' object which is a type, since

>>> type(str)
<type 'type'>

Using this 'type' object I could access the string methods like they were static functions.

>>> str.center('a',5)
'  a  '

Alas! This violates the zen of python.

There should be one-- and preferably only one --obvious way to do it.

Even the types of these two methods are different.

>>> type(str.center)
<type 'method_descriptor'>
>>> type('Ni!'.center)
<type 'builtin_function_or_method'>

Now,

  1. Is this an example of how classes in python should be designed?
  2. Why are the types different?
  3. What is a method_descriptor and why should I bother?

Thanks for the answers!

解决方案

That's simply how classes in Python work:

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

When you say o.method(1) you can think of it as a shorthand for C.method(o, 1). A method_descriptor is part of the machinery that makes that work.

这篇关于Python 中 str 的静态与实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆