Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的不同函数?_Python_Function - Fatal编程技术网

Python中的不同函数?

Python中的不同函数?,python,function,Python,Function,为何我可以这样说: print (max('abcdefg')) print (sorted('akjsdhfjkh')) 但不是这个: print(capitalize(cat) 而是: v='cat' print (v.capitalize()) max,sorted是常规内置函数 In [30]: max Out[30]: <function max> 大写是字符串对象的一种方法: sorted和max是内置函数: 简短回答: 没有什么意义——只是为这些函数选择了调用

为何我可以这样说:

print (max('abcdefg'))
print (sorted('akjsdhfjkh'))
但不是这个:

print(capitalize(cat)
而是:

v='cat'
print (v.capitalize())

max
sorted
是常规内置函数

In [30]: max
Out[30]: <function max>

大写是字符串对象的一种方法:

sorted和max是内置函数: 简短回答:

没有什么意义——只是为这些函数选择了调用约定

稍长一点的回答:

max()和sorted()是对序列进行操作的函数——给它们一个序列(列表、元组或字符串),它们返回一个新的序列


capitalize()是str对象的一种方法。与其中许多方法一样,还有一个str包方法接受参数。因此,如果您愿意,可以这样称呼它:
str.capitalize(v)
这里没有逻辑。
您完全正确地认为,任何类型的iterable数据结构(如字符串或列表)都应该具有内置的max函数

i、 e

Python的创建者选择了少量他们希望被视为内置的操作:

大多数其他函数都是特定类或对象的一部分。
我认为max不是内置的,而是某个数学库的一部分,这是完全合理的

i、 e


查找方法和函数之间的差异。主要区别在于,我们可以独立操作函数,而在使用方法的情况下,我们必须将其用于特定的对象

你可以做
'cat'。顺便说一句,大写()

在Python中,有函数和方法。函数可以自己调用。需要从其类的对象调用方法

假设您有一个python文件:

def my_print1():       # this is a function
   print("cats are nice")

class test():
    def my_print2():   # this is a method
        print("dogs are nice")
要调用my_print1函数只需执行
my_print1()
,它就会显示猫很好。 但是要调用my_print2方法您需要一个类为
test
的对象,然后该对象可以调用my_print2方法。以下是如何在代码中实现这一点:

myObject = test()      # this creates an object of class test
myObject.my_print2()   # this calls the method using that object
看到我的打印2是如何使用对象调用的吗?这就像做
v.capitalize()
v
这里是内置
str
(string)类的一个对象,而
capitalize
是该类的一个方法,因此需要从中调用一个对象(v)

max
sorted
是python的内置函数。它们可以在不需要对象的情况下被调用


是python的内置函数。

可能重复为什么不工作?def oneToN(n):如果n==1:返回1,否则:返回n+oneToN(n-1)
import math
math.max('abcdefg')
def my_print1():       # this is a function
   print("cats are nice")

class test():
    def my_print2():   # this is a method
        print("dogs are nice")
myObject = test()      # this creates an object of class test
myObject.my_print2()   # this calls the method using that object