189 8069 5689

nop函数Python nop函数是干什么的

Python中定义函数默认参数值的使用注意事项?

4.7.1. 默认参数值

成都创新互联凭借专业的设计团队扎实的技术支持、优质高效的服务意识和丰厚的资源优势,提供专业的网站策划、网站制作、做网站、网站优化、软件开发、网站改版等服务,在成都10余年的网站建设设计经验,为成都上千家中小型企业策划设计了网站。

最常用的一种形式是为一个或多个参数指定默认值。这会创建一个可以使用比定义是允许的参数更少的参数调用的函数,例如:

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):

while True:

ok = input(prompt)

if ok in ('y', 'ye', 'yes'):

return True

if ok in ('n', 'no', 'nop', 'nope'):

return False

retries = retries - 1

if retries 0:

raise OSError('uncooperative user')

print(complaint)

这个函数可以通过几种不同的方式调用:

只给出必要的参数:

ask_ok('Do you really want to quit?')

给出一个可选的参数:

ask_ok('OK to overwrite the file?', 2)

或者给出所有的参数:

ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

这个例子还介绍了 in 关键字。它测定序列中是否包含某个确定的值。

默认值在函数 定义 作用域被解析,如下所示:

i = 5

def f(arg=i):

print(arg)

i = 6

f()

将会输出 5。

重要警告: 默认值只被赋值一次。这使得当默认值是可变对象时会有所不同,比如列表、字典或者大多数类的实例。例如,下面的函数在后续调用过程中会累积(前面)传给它的参数:

def f(a, L=[]):

L.append(a)

return L

print(f(1))

print(f(2))

print(f(3))

这将输出:

[1]

[1, 2]

[1, 2, 3]

如果你不想让默认值在后续调用中累积,你可以像下面一样定义函数:

def f(a, L=None):

if L is None:

L = []

L.append(a)

return L

Python的函数参数总结

import math

a = abs

print(a(-1))

n1 = 255

print(str(hex(n1)))

def my_abs(x):

# 增加了参数的检查

if not isinstance(x, (int, float)):

raise TypeError('bad operand type')

if x = 0:

return x

else:

return -x

print(my_abs(-3))

def nop():

pass

if n1 = 255:

pass

def move(x, y, step, angle=0):

nx = x + step * math.cos(angle)

ny = y - step * math.sin(angle)

return nx, ny

x, y = move(100, 100, 60, math.pi / 6)

print(x, y)

tup = move(100, 100, 60, math.pi / 6)

print(tup)

print(isinstance(tup, tuple))

def quadratic(a, b, c):

k = b * b - 4 * a * c

# print(k)

# print(math.sqrt(k))

if k 0:

print('This is no result!')

return None

elif k == 0:

x1 = -(b / 2 * a)

x2 = x1

return x1, x2

else:

x1 = (-b + math.sqrt(k)) / (2 * a)

x2 = (-b - math.sqrt(k)) / (2 * a)

return x1, x2

print(quadratic(2, 3, 1))

def power(x, n=2):

s = 1

while n 0:

n = n - 1

s = s * x

return s

print(power(2))

print(power(2, 3))

def enroll(name, gender, age=8, city='BeiJing'):

print('name:', name)

print('gender:', gender)

print('age:', age)

print('city:', city)

enroll('elder', 'F')

enroll('android', 'B', 9)

enroll('pythone', '6', city='AnShan')

def add_end(L=[]):

L.append('end')

return L

print(add_end())

print(add_end())

print(add_end())

def add_end_none(L=None):

if L is None:

L = []

L.append('END')

return L

print(add_end_none())

print(add_end_none())

print(add_end_none())

def calc(*nums):

sum = 0

for n in nums:

sum = sum + n * n

return sum

print(calc(1, 2, 3))

print(calc())

l = [1, 2, 3, 4]

print(calc(*l))

def foo(x, y):

print('x is %s' % x)

print('y is %s' % y)

foo(1, 2)

foo(y=1, x=2)

def person(name, age, **kv):

print('name:', name, 'age:', age, 'other:', kv)

person('Elder', '8')

person('Android', '9', city='BeiJing', Edu='人民大学')

extra = {'city': 'Beijing', 'job': 'Engineer'}

person('Jack', 24, **extra)

def person2(name, age, *, city, job):

print(name, age, city, job)

person2('Pthon', 8, city='BeiJing', job='Android Engineer')

def person3(name, age, *other, city='BeiJing', job='Android Engineer'):

print(name, age, other, city, job)

person3('Php', 18, 'test', 1, 2, 3)

person3('Php2', 28, 'test', 1, 2, 3, city='ShangHai', job='Pyhton Engineer')

def test2(a, b, c=0, *args, key=None, **kw):

print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'key=', key, 'kw =', kw)

test2(1, 2, 3, 'a', 'b', 'c', key='key', other='extra')

args = (1, 2, 3, 4)

kw = {'d': 99, 'x': '#'}

test2(*args, **kw)

如何在Python中定义静态变量

Python使用函数默认值实现函数静态变量的方法,具体方法如下:

一、Python函数默认值

Python函数默认值的使用可以在函数调用时写代码提供方便,很多时候我们只要使用默认值就可以了。 所以函数默认值在python中用到的很多,尤其是在类中间,类的初始化函数中一帮都会用到默认值。 使用类时能够方便的创建类,而不需要传递一堆参数。

只要在函数参数名后面加上 ”=defalut_value”,函数默认值就定义好了。有一个地方需要注意的是,有默认值的参数必须在函数参数列表的最后,不允许将没有默认值的参数放在有默认值的参数后,因为如果你那样定义的话,解释器将不知道如何去传递参数。

先来看一段示例代码:

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):

while True:

ok = raw_input(prompt)

if ok in ('y', 'ye', 'yes'): return True

if ok in ('n', 'no', 'nop', 'nope'): return False

retries = retries - 1

if retries 0: raise IOError, 'refusenik user'

print complaint

你调用上面的函数时,可以修改重试次数和输出的提示语言,如果你比较懒得话,那么什么都不用改。

二、python使用函数默认值来实现函数静态变量的功能

Python中是不支持静态变量的,但是我们可以通过函数的默认值来实现静态变量的功能。

当函数的默认值是内容是可变的类时,类的内容可变,而类的名字没变。(相当于开辟的内存区域没有变,而其中内容可以变化)。

这是因为python中函数的默认值只会被执行一次,(和静态变量一样,静态变量初始化也是被执行一次。)这就是他们的共同点。

再来看下面的程序片段:

def f(a, L=[]):

L.append(a)

return L

print f(1)

print f(2)

print f(3)

print f(4,['x'])

print f(5)

其输出结果是:

[1]

[1, 2]

[1, 2, 3]

['x', 4]

[1, 2, 3, 5]

前面的好理解,为什么最后 “print f(5)”的输出是 “[1, 2, 3, 5]”呢?

这是因为 “print f(4,['x'])”时,默认变量并没有被改变,因为默认变量的初始化只是被执行了一次(第一次使用默认值调用),初始化执行开辟的内存区(我们可以称之为默认变量)没有被改变,所以最后的输出结果是“[1, 2, 3, 5]”。


文章标题:nop函数Python nop函数是干什么的
本文路径:http://cdxtjz.cn/article/doiighi.html

其他资讯