Python: item.method() 和函数(项目)

Python: item.method() and function(item)

选择一些方法以它们一起使用的项目作为前缀,但有些是需要项目作为参数的函数的逻辑是什么? 例如:

    L=[1,4,3]    
    print len(L)  #function(item)  
    L.sort()  #item.method()            

我想也许修改项目的函数需要加上前缀,而 return 关于项目的信息的函数将它用作参数,但我不太确定。

编辑:

我想问的是为什么python没有L.len()?这两种函数的性质有什么区别?还是随机选择了一些操作是方法而一些是函数?

一些可以帮助您更好地理解的内容:http://www.tutorialspoint.com/python/python_classes_objects.htm

你描述的item.function()实际上是一个方法,由item所属的class定义。您需要对 functionclassobjectmethod 以及 Python.

中的更多内容形成全面的了解

仅从概念上讲,当您调用 L.sort() 时,type/class listsort() 方法实际上接受一个通常按照约定称为 self 的参数,即表示 type/class list 的 object/instance,在本例中为 Lsort 就像一个独立的 sorted 函数,只是将排序逻辑应用于 L itself。相比之下,sorted 函数需要一个可迭代对象(例如 list)作为其必需的参数才能运行。

代码示例:

my_list = [2, 1, 3]

# .sort() is a list method that applies the sorting logic to a
# specific instance of list, in this case, my_list
my_list.sort()

# sorted is a built-in function that's more generic which can be
# used on any iterable of Python, including list type
sorted(my_list)

Python 背后的原则之一是 There is Only One Way to Do It。特别是,要获取序列的长度(数组/元组/xrange...),无论序列类型如何,您总是使用 len

但是,并非所有这些序列类型都支持排序。这使它更适合作为一种方法。

a = [0,1,2]
b = (0,1,2)
c = xrange(3)
d = "abc"

print len(a), len(b), len(c), len(d) # Ok

a.sort() # Ok
b.sort() # AttributeError: 'tuple' object has no attribute 'sort'
c.sort() # AttributeError: 'xrange' object has no attribute 'sort'
d.sort() # AttributeError: 'str' object has no attribute 'sort'

方法和函数之间的区别不仅仅在于它们的语法。

def foo():
    print "function!"

class ExampleClass(object):
    def foo(self):
        print "method!"

在这个例子中,我定义了一个函数 foo 和一个 class ExampleClass 与 1 方法 foo。 让我们尝试使用它们:

>>> foo()
function!
>>> e = ExampleClass()
>>> e.foo()
method!
>>> l = [3,4,5]
>>> l.foo()

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    l.foo()
AttributeError: 'list' object has no attribute 'foo'
>>> 

即使两者具有相同的名称,Python 知道如果您执行 foo(),您调用的是一个函数,因此它会检查是否有任何函数定义为该名称。

如果你执行 a.foo(),它知道你正在调用一个方法,所以它会检查是否有为类型 [=16= 的对象定义的方法 foo ] 有,有的话就调用。在最后一个例子中,我们用一个列表来尝试,它给了我们一个错误,因为列表没有定义 foo 方法。