这篇文章是python大全第一篇文章,来介绍进阶版函数!如果你们还没有读过之前的文章的话最好回去读一下!
专栏介绍:何为深度聊天?<--包括python大全介绍
目录
好的,咱们废话不多说,进入正题!
一、何为函数
函数,就像下面这样:
def hanshu():
print("我是一个函数")
这就是最简单的函数。调用函数的方法如下:
hanshu()
打印结果:
"我是一个函数"
这就是函数。可是函数不能只有这些东西,我们要进阶一下。
二、带参数的函数
2.1.一般参数
一般参数如下:
def hanshu(text):
print(text + "<--输出结果")
调用函数时要在括号内加入参数:
hanshu("我是一个函数!")
结果为:
"我是一个函数 <--输出结果"
2.2.等于参数
先看一下用法:
def hanshu(text = None):
print(text)
hanshu()
结果不会报错,会写出一个None!
那怎样才能更改text值呢?
下面就是方法!
hanshu(text = "我是一个函数")
参数是不是有很多用法呢?
具体实例(结合两种):
def hanshu(text, n = None):
print(text, "=", n)
print("你觉得对吗?")
三、递归函数
何为递归呢?下面内容可以解释(又来自百度百科)
程序调用自身的编程技巧称为递归( recursion)。递归作为一种算法在程序设计语言中广泛应用。 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。
那么我们举几个例子吧!
3.1.斐波那契数列
def Fibo(n):
# 出口
if n == 1 or n == 2:
return 1
else:
return Fibo(n - 1) + Fibo(n - 2)
这就是一个斐波那契数列。
3.2.三以内数字累加和:
# 3 + 2 + 1
def sum_numbers(num):
# 1.如果是1,直接返回1 -- 出口
if num == 1:
return 1
# 2.如果不是1,重复执行累加并返回结果
return num + sum_numbers(num-1)
sum_result = sum_numbers(3)
# 输出结果为6
print(sum_result)
这就是累加和算法
还有很多递归算法等着大家去使用哦。
四、包,库函数
咱们来看一看math库里的函数吧:
import math as _math
import warnings as _warnings
from operator import mul as _mul
def clamp(num, min_val, max_val):
return max(min(num, max_val), min_val)
class Vec2(tuple):
"""A two dimensional vector represented as an X Y coordinate pair.
:parameters:
`x` : int or float :
The X coordinate of the vector.
`y` : int or float :
The Y coordinate of the vector.
Vectors must be created with either 0 or 2 values. If no arguments are provided a vector with the coordinates 0, 0 is created.
Vectors are stored as a tuple and therefore immutable and cannot be modified directly
"""
def __new__(cls, *args):
assert len(args) in (0, 2), "0 or 2 values are required for Vec2 types."
return super().__new__(Vec2, args or (0, 0))
@staticmethod
def from_polar(mag, angle):
"""Create a new vector from the given polar coodinates.
:parameters:
`mag` : int or float :
The magnitude of the vector.
`angle` : int or float :
The angle of the vector in radians.
:returns: A new vector with the given angle and magnitude.
:rtype: Vec2
"""
return Vec2(mag * _math.cos(angle), mag * _math.sin(angle))
@property
def x(self):
"""The X coordinate of the vector.
:type: float
"""
return self[0]
@property
def y(self):
"""The Y coordinate of the vector.
:type: float
"""
return self[1]
@property
def heading(self):
"""The angle of the vector in radians.
:type: float
"""
return _math.atan2(self[1], self[0])
@property
def mag(self):
"""The magnitude, or length of the vector. The distance between the coordinates and the origin.
Alias of abs(self).
:type: float
"""
return self.__abs__()
def __add__(self, other):
return Vec2(self[0] + other[0], self[1] + other[1])
def __sub__(self, other):
return Vec2(self[0] - other[0], self[1] - other[1])
def __mul__(self, other):
return Vec2(self[0] * other[0], self[1] * other[1])
def __truediv__(self, other):
return Vec2(self[0] / other[0], self[1] / other[1])
def __abs__(self):
return _math.sqrt(self[0] ** 2 + self[1] ** 2)
def __neg__(self):
return Vec2(-self[0], -self[1])
def __round__(self, ndigits=None):
return Vec2(*(round(v, ndigits) for v in self))
def __radd__(self, other):
"""Reverse add. Required for functionality with sum()
"""
if other == 0:
return self
else:
return self.__add__(other)
def from_magnitude(self, magnitude):
"""Create a new Vector of the given magnitude by normalizing, then scaling the vector. The heading remains unchanged.
:parameters:
`magnitude` : int or float :
The magnitude of the new vector.
:returns: A new vector with the magnitude.
:rtype: Vec2
"""
return self.normalize().scale(magnitude)
def from_heading(self, heading):
"""Create a new vector of the same magnitude with the given heading. I.e. Rotate the vector to the heading.
:parameters:
`heading` : int or float :
The angle of the new vector in radians.
:returns: A new vector with the given heading.
:rtype: Vec2
"""
mag = self.__abs__()
return Vec2(mag * _math.cos(heading), mag * _math.sin(heading))
def limit(self, max):
"""Limit the magnitude of the vector to the value used for the max parameter.
:parameters:
`max` : int or float :
The maximum magnitude for the vector.
:returns: Either self or a new vector with the maximum magnitude.
:rtype: Vec2
"""
if self[0] ** 2 + self[1] ** 2 > max * max:
return self.from_magnitude(max)
return self
def lerp(self, other, alpha):
"""Create a new vector lineraly interpolated between this vector and another vector.
:parameters:
`other` : Vec2 :
The vector to be linerly interpolated to.
`alpha` : float or int :
The amount of interpolation.
Some value between 0.0 (this vector) and 1.0 (other vector).
0.5 is halfway inbetween.
:returns: A new interpolated vector.
:rtype: Vec2
"""
return Vec2(self[0] + (alpha * (other[0] - self[0])),
self[1] + (alpha * (other[1] - self[1])))
def scale(self, value):
"""Multiply the vector by a scalar value.
:parameters:
`value` : int or float :
The ammount to be scaled by
:returns: A new vector scaled by the value.
:rtype: Vec2
"""
return Vec2(self[0] * value, self[1] * value)
def rotate(self, angle):
"""Create a new Vector rotated by the angle. The magnitude remains unchanged.
:parameters:
`angle` : int or float :
The angle to rotate by
:returns: A new rotated vector of the same magnitude.
:rtype: Vec2
"""
mag = self.mag
heading = self.heading
return Vec2(mag * _math.cos(heading + angle), mag * _math.sin(heading+angle))
def distance(self, other):
"""Calculate the distance between this vector and another 2D vector.
:parameters:
`other` : Vec2 :
The other vector
:returns: The distance between the two vectors.
:rtype: float
"""
return _math.sqrt(((other[0] - self[0]) ** 2) + ((other[1] - self[1]) ** 2))
def normalize(self):
"""Normalize the vector to have a magnitude of 1. i.e. make it a unit vector.
:returns: A unit vector with the same heading.
:rtype: Vec2
"""
d = self.__abs__()
if d:
return Vec2(self[0] / d, self[1] / d)
return self
def clamp(self, min_val, max_val):
"""Restrict the value of the X and Y components of the vector to be within the given values.
:parameters:
`min_val` : int or float :
The minimum value
`max_val` : int or float :
The maximum value
:returns: A new vector with clamped X and Y components.
:rtype: Vec2
"""
return Vec2(clamp(self[0], min_val, max_val), clamp(self[1], min_val, max_val))
def dot(self, other):
"""Calculate the dot product of this vector and another 2D vector.
:parameters:
`other` : Vec2 :
The other vector.
:returns: The dot product of the two vectors.
:rtype: float
"""
return self[0] * other[0] + self[1] * other[1]
def __getattr__(self, attrs):
try:
# Allow swizzed getting of attrs
vec_class = {2: Vec2, 3: Vec3, 4: Vec4}.get(len(attrs))
return vec_class(*(self['xy'.index(c)] for c in attrs))
except Exception:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attrs}'")
def __repr__(self):
return f"Vec2({self[0]}, {self[1]})"
只列举一部分内容,谢谢!
好的,咱们来看一看写法:(我拿出我写的mod.system)
记住,文件位置最好在你的c盘中的python3.x文件里的Lib,里面可以新建文件夹,里面可以写上__init__.py,然后再写上另一个程序,名字随便。或者直接在Lib里面创建一个py文件,名字随意。
方法:
def Print(text):
print(text)
调用(记住,在3.10里面的就要在3.10里面调用。否则要报错。)
>>>import mod.system
>>>mod.system.Print("xxx")
"xxx"
>>>from mod import system
>>>system.Print("xxx")
"xxx"
>>>from mod.system import Print
>>>Print("xxx")
"xxx"
是不是很简单?
四、return
return这个东西,是只能放在函数里面的,否则要报错!
return是干什么的?
来举个例子:
def hanshu(n):
if n <= 0:
return False
else:
return True
n = hanshu(3)
print(n)
# 结果
True
搞懂了return了吗?return就是返回一个值,可以赋值变量哦~
是不是很神奇?
五、类里面的函数
5.1.自制函数
之前讲过,我就不细讲了。
class Human():
def say(self):
print("I am a human")
human = Human()
human.say()
5.2.内置函数
__init__就是最常见的一个函数了:
class Human():
def __init__(self, age, height):
self.age = age
self.height = height
human = Human(12, 35)
六、深度聊聊python函数
python函数十分有用。为什么这么说?
python函数不仅有参数,还有return等等有用的东西。
阶乘,递归,逆推,正推都有用。并且还可以用在类里面。
函数虽然难,但是他功能齐全,真的十分好用!
七、总结
python有很多东西,print, list, tuple, int, str, float, bool, map, sum, eval, lambda, while, for, range...这些东西都是由一样东西做出来的,那就是函数。