python函数进阶小结 python函数总结

python函数与方法的区别总结1、函数的分类:
内置函数:python内嵌的一些函数 。
匿名函数:一行代码实现一个函数功能 。
递归函数
自定义函数:根据自己的需求,来进行定义函数 。
2、方法的分类:
普通方法:直接用self调用的方法 。
私有方法:__函数名,只能在类中被调用的方法 。
属性方法:@property,将方法伪装成为属性,让代码看起来更合理 。
特殊方法(双下划线方法):以__init__为例,是用来封装实例化对象的属性,只要是实例化对象就一定会执行__init方法,如果对象子类中没有则会寻找父类(超类) , 如果父类(超类)也没有,则直接继承object(python 3.x)类,执行类中的__init__方法 。类方法:通过类名的调用去操作公共模板中的属性和方法 。
静态方法:不用传入类空间、对象的方法,作用是保证代码的一致性,规范性,可以完全独立类外的一个方法,但是为了代码的一致性统一的放到某个模块(py文件)中 。
其次,从作用域的角度来分析:
(1)函数作用域:从函数调用开始至函数执行完成 , 返回给调用者后,在执行过程中开辟的空间会自动释放,也就是说函数执行完成后,函数体内部通过赋值等方式修改变量的值不会保留,会随着返回给调用者后,开辟的空间会自动释放 。
(2)方法作用域:通过实例化的对象进行方法的调用,调用后开辟的空间不会释放,也就是说调用方法中对变量的修改值会一直保留 。
最后,调用的方式不同 。
(1)函数:通过“函数名()”的方式进行调用 。
(2)方法:通过“对象.方法名”的方式进行调用 。
Python的函数参数总结import math
a = abs
print(a(-1))
n1 = 255
print(str(hex(n1)))
def my_abs(x):
# 增加python函数进阶小结了参数python函数进阶小结的检查
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 k0:
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 n0:
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))

推荐阅读