Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

string - Static vs instance methods of str in Python

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...