为什么有些方法使用点符号而其他方法没有?

Fis*_*shy 16 python methods syntax

所以,我刚开始学习Python(使用Codecademy),我有点困惑.

为什么有一些方法需要参数,而其他方法使用点符号?

len()采用了一个arugment,但是不能使用点符号:

>>> len("Help")
4
>>>"help".len()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'len'
Run Code Online (Sandbox Code Playgroud)

同样地:

>>>"help".upper()
'HELP'
>>>upper("help")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'upper' is not defined
Run Code Online (Sandbox Code Playgroud)

Mal*_*imi 18

这里的关键词是方法.函数和方法之间存在细微差别.

方法

是在给定对象的类中定义的函数.例如:

class Dog:
    def bark(self):
        print 'Woof woof!'

rufus = Dog()
rufus.bark() # called from the object
Run Code Online (Sandbox Code Playgroud)

功能

函数是全局定义的过程:

def bark():
    print 'Woof woof!'
Run Code Online (Sandbox Code Playgroud)

至于关于len函数的问题,全局定义的函数调用对象的__len__特殊方法.所以在这种情况下,这是一个可读性问题.

否则,当它们仅应用于某些对象时,方法会更好.应用于多个对象时,函数更好.例如,你怎么能大写一个数字?您不会将其定义为函数,您只能将其定义为仅在字符串类中的方法.

  • 所以,只是为了确认 - 在我上面的例子中, len() 是一个全局函数,而 upper() 是字符串类的方法? (3认同)
  • 鱼,说得对。当方法仅适用于某些对象时,方法会更好。当函数应用于多个对象时,它们会更好。例如,如何将数字大写。您可以将其定义为函数,而将其定义为仅字符串方法。 (3认同)