Kaggle翻译,第二天:python2/7

函数和获取帮助——Python 2/7

调用函数和定义我们自己和使用Python的内置文档

你已经看到和使用函数如printabs等。但Python有更多的功能,并定义自己的函数是Python编程的巨头。
在本课中,您将学习更多使用和定义函数的详情。

获取帮助

  • 你在前面的课程看到abs函数,但是如果你忘了它做什么怎么办?
  • help()函数可能是你学习的最重要的Python功能。如果你能记得如何使用help(),将是你了解大多数其他功能的关键。
  • 下面是一个示例:
help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.
  • help()显示两件事:
  • 该函数的声明 round(number, ndigits=None)。在这种情况下,这告诉我们,round() 接受一个参数,我们可以形容为数字。此外,我们可以选择给名为ndigits的一个单独的参数。
  • 函数做什么的简单英语描述。
  • 常见的陷阱:当你正在查找函数帮助时,记得传递函数本身的名称,而不是调用该函数的语句。

如果我们对round()函数调用语句使用帮助会发生什么呢?

help(round(-2.01))
Help on int object:

class int(object)
 |  int([x]) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __and__(self, value, /)
 |      Return self&value.
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __ceil__(...)
 |      Ceiling of an Integral returns itself.
 |  
 |  __divmod__(self, value, /)
 |      Return divmod(self, value).
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __float__(self, /)
 |      float(self)
 |  
 |  __floor__(...)
 |      Flooring an Integral returns itself.
 |  
 |  __floordiv__(self, value, /)
 |      Return self//value.
 |  
 |  __format__(self, format_spec, /)
 |      Default object formatter.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getnewargs__(self, /)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __index__(self, /)
 |      Return self converted to an integer, if self is suitable for use as an index into a list.
 |  
 |  __int__(self, /)
 |      int(self)
 |  
 |  __invert__(self, /)
 |      ~self
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lshift__(self, value, /)
 |      Return self<<value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __neg__(self, /)
 |      -self
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __pos__(self, /)
 |      +self
 |  
 |  __pow__(self, value, mod=None, /)
 |      Return pow(self, value, mod).
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __rand__(self, value, /)
 |      Return value&self.
 |  
 |  __rdivmod__(self, value, /)
 |      Return divmod(value, self).
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rfloordiv__(self, value, /)
 |      Return value//self.
 |  
 |  __rlshift__(self, value, /)
 |      Return value<<self.
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __round__(...)
 |      Rounding an Integral returns itself.
 |      Rounding with an ndigits argument also returns an integer.
 |  
 |  __rpow__(self, value, mod=None, /)
 |      Return pow(value, self, mod).
 |  
 |  __rrshift__(self, value, /)
 |      Return value>>self.
 |  
 |  __rshift__(self, value, /)
 |      Return self>>value.
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rtruediv__(self, value, /)
 |      Return value/self.
 |  
 |  __rxor__(self, value, /)
 |      Return value^self.
 |  
 |  __sizeof__(self, /)
 |      Returns size in memory, in bytes.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __truediv__(self, value, /)
 |      Return self/value.
 |  
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |  
 |  __xor__(self, value, /)
 |      Return self^value.
 |  
 |  bit_length(self, /)
 |      Number of bits necessary to represent self in binary.
 |      
 |      >>> bin(37)
 |      '0b100101'
 |      >>> (37).bit_length()
 |      6
 |  
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |  
 |  to_bytes(self, /, length, byteorder, *, signed=False)
 |      Return an array of bytes representing an integer.
 |      
 |      length
 |        Length of bytes object to use.  An OverflowError is raised if the
 |        integer is not representable with the given number of bytes.
 |      byteorder
 |        The byte order used to represent the integer.  If byteorder is 'big',
 |        the most significant byte is at the beginning of the byte array.  If
 |        byteorder is 'little', the most significant byte is at the end of the
 |        byte array.  To request the native byte order of the host system, use
 |        `sys.byteorder' as the byte order value.
 |      signed
 |        Determines whether two's complement is used to represent the integer.
 |        If signed is False and a negative integer is given, an OverflowError
 |        is raised.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  from_bytes(bytes, byteorder, *, signed=False) from builtins.type
 |      Return the integer represented by the given array of bytes.
 |      
 |      bytes
 |        Holds the array of bytes to convert.  The argument must either
 |        support the buffer protocol or be an iterable object producing bytes.
 |        Bytes and bytearray are examples of built-in objects that support the
 |        buffer protocol.
 |      byteorder
 |        The byte order used to represent the integer.  If byteorder is 'big',
 |        the most significant byte is at the beginning of the byte array.  If
 |        byteorder is 'little', the most significant byte is at the end of the
 |        byte array.  To request the native byte order of the host system, use
 |        `sys.byteorder' as the byte order value.
 |      signed
 |        Indicates whether two's complement is used to represent the integer.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  denominator
 |      the denominator of a rational number in lowest terms
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  numerator
 |      the numerator of a rational number in lowest terms
 |  
 |  real
 |      the real part of a complex number
  • Python从内到外分析这样的表达式。首先,它计算round(-2.01) 的值,再为这个表达式的输出做解释和帮助。

实际上Integer有很多要说的内容! 在我们介绍完Python中的对象、方法、和属性后,这个输出的解释就会更好理解了。

  • round() 是一个非常简单的函数,他的说明文档并不长。help在处理更复杂的、可配置的函数如print。如果下面的输出看起来不可思议的,别担心…。现在,看看你能否从这个帮助文档中发现新的东西。
help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
  • 如果你查找它的文档,你会发现print带参数叫做sep,这规定了我们在传入多个打印参数时,彼此之间的间隔符。

函数定义

  • 内置函数很棒,但在我们需要开始定义自己的函数之前,我们编程走不了多远。
  • 下面是一个简单的示例:
def least_difference(a, b, c):
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)
  • 这里创建了一个函数叫least_difference,它使用三个参数a bc
  • 函数首先由def关键字开头。: 随后的缩进代码块说明了当调用该函数时是如何运行的运行。
  • return是另一个功能相关联的独特的关键字。从Python遇到return语句时,它立即退出函数,并在右边的值传递给调用上下文。
  • 能否从源代码弄清楚least_difference()的功能?
  • 如果我们还不确定我们可以试试几个例子:
print(
    least_difference(1, 10, 100),
    least_difference(1, 10, 10),
    least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?
)
9 0 1
  • 或许help()函数可以告诉我们一些关于它的信息。
help(least_difference)
Help on function least_difference in module __main__:

least_difference(a, b, c)
  • Python还没有智能化到读取我的源码再把它转化成英文描述。但是,当我定义一个函数时,我可以提供一种叫文档字符串的说明。

文档字符串(Docstrings)

def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among a, b and c.
    
    >>> least_difference(1, 5, -5)
    4
    """
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)
  • 文档字符串是一个三引号字符串(可以跨多个行),它紧跟在该函数的头后。在我们所谓的help() 时,它显示这串文档字符串。
help(least_difference)
Help on function least_difference in module __main__:

least_difference(a, b, c)
    Return the smallest difference between any two numbers
    among a, b and c.
    
    >>> least_difference(1, 5, -5)
    4

:文档字符串中的最后两行是一个示例函数调用和结果。(>>>是对Python交互式shell中使用命令提示符的引用。)Python不是真正的运行该示例——它只是为了方便读者理解。在文档字符串中囊括一至多个例子的做法并不常见,但它可以是非常有效地帮助别人了解你的函数。真实的例子详情见numpy的文档字符串 中的np.eye

  • 好的程序员使用docstring,除非他们想在使用之后迅速报废这块代码,(这是极其少见的)。所以,你也应该开始写字符串。

没有返回值的函数

  • 如果我们不在函数代码中引入return关键字会发生什么?
def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among a, b and c.
    """
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    min(diff1, diff2, diff3)
    
print(
    least_difference(1, 10, 100),
    least_difference(1, 10, 10),
    least_difference(5, 6, 7),
)
None None None
  • Python允许我们定义这样的函数。他们返回的结果固定为None。(这个和许多其它语言中的null时一个意思)
  • 没有返回语句,least_difference完全没有意义,但具有其他作用的函数不返回任何可能做一些有用的事。我们已经看到了这两个例子:print()help()不返回任何值。我们只要求他们对其特殊作用(在屏幕上输出一些文本)。其他有用的特殊作用的例子包括写入文件或修改输入。
mystery = print()
print(mystery)
None

默认参数值

  • 当我们调用help(print)我们看到print函数有几个可选参数。如我们可以为sep指定一些值,来在要求输出的几个参数之间插入特定字符
print(1, 2, 3, sep=' < ')
1 < 2 < 3
  • 但是如果我们不指定,那么参数之间的间隔就是默认的' '(一个空格)。
print(1, 2, 3)
1 2 3
  • 在我们自己定义的函数中指定可选参数的默认值也相当容易:
def greet(who="Colin"):
    print("Hello,", who)
    
greet()
greet(who="Kaggle")
# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)
greet("world")
Hello, Colin
Hello, Kaggle
Hello, world

函数中调用函数

  • 这里有一个强大但是很抽象的功能。你可以将函数作为参数传给其他函数。一些例子长得像这样:
def mult_by_five(x):
    return 5 * x

def call(fn, arg):
    """Call fn on arg"""
    return fn(arg)

def squared_call(fn, arg):
    """Call fn on the result of calling fn on arg"""
    return fn(fn(arg))

print(
    call(mult_by_five, 1),
    squared_call(mult_by_five, 1), 
    sep='\n', # '\n' is the newline character - it starts a new line
)
5
25
  • 操作其他功能的函数被称为"高阶函数。"你可能最近不会写自己的高阶函数。但有内置到Python的高阶函数,您可能会发现很有用。
  • 这有一个使用函数max的有趣的例子:
  • 默认情况下,max函数返回其传入参数的最大值。但如果我们通过在使用可选的key参数传入一个函数,它返回参数x,是最大化的key(x)(又名’argmax’)。
def mod_5(x):
    """Return the remainder of x after dividing by 5"""
    return x % 5

print(
    'Which number is biggest?',
    max(100, 51, 14),
    'Which number is the biggest modulo 5?',
    max(100, 51, 14, key=mod_5),
    sep='\n',
)
Which number is biggest?
100
Which number is the biggest modulo 5?
14
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值