Skip to content

函数与类

函数

函数是指将不同位置多次调用的代码封打包方便使用

模板

py
def 函数名(形参):
    代码块

例如:

py
def say_hello():
    print("你好")

函数参数

py
def say_hello(name):
    print(f"你好,{name}")

函数返回值

py
def add(a,b):
    return a + b

训练

设计一个函数add,提供ab两个数,返回最大的值

shell
例如:
    输入 1,2
    返回 2
py
result = add(1,2)
print(result) # 2
点我查看答案
py
def add(a,b):
    if a > b:
        return a
    return b

类与函数类似,类是函数的合集

py
class Person:
    def say_hello(self): 
        print("你好")


# 使用方式
person = Person()
person.say_hello()

提示

在类中的函数,必须拥有一个self参数

训练

设计一个Circle类,并设计两个函数get_perimeterget_area,打印半径分别为1015的圆的周长与面积,结果保留2位小数

py
class Circle:
    # 计算周长
    def get_perimeter(self, radius):
        pass

    # 计算面积
    def get_area(self, radius):
        pass
点我查看答案
py
import math

class Circle:
    def get_perimeter(self, radius):
        return 2 * math.pi * radius

    def get_area(self, radius):
        return math.pi * radius ** 2

# 实例化
circle = Circle()

# 半径10
p1 = circle.get_perimeter(10)
a1 = circle.get_area(10)
print(f"半径10:周长={p1:.2f},面积={a1:.2f}")

# 半径15
p2 = circle.get_perimeter(15)
a2 = circle.get_area(15)
print(f"半径15:周长={p2:.2f},面积={a2:.2f}")