Static vs instance methods of str in Python

后端 未结 5 1173
鱼传尺愫
鱼传尺愫 2020-12-06 07:03

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

5条回答
  •  旧巷少年郎
    2020-12-06 07:39

    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.

提交回复
热议问题