Python中的函数和方法概要

Python中的函数和方法概要

1. 函数(Function)

定义:独立存在,不依赖类或对象。

调用方式:直接通过函数名调用。

参数传递:显式传递所有参数。

示例

# 独立函数
def add(a, b):
    return a + b

print(add(3, 5))  # 输出8

2. 方法(Method)

定义:定义在类内部(方法是定义在类内部的函数),分为三种类型:

☆实例方法:操作对象实例(绑定到对象)。

☆类方法:用于操作类状态(类属性)或提供替代构造函数(绑定到类)。定义时需使用@classmethod装饰器,第一个参数约定为cls,代表类本身的引用。可通过类名或实例名调用。

☆静态方法:定义在类内部,但既不绑定到对象实例也不绑定到类,定义时需使用@staticmethod装饰器,无隐式参数。它逻辑上不依赖特定实例或类状态,通常用于组织与类相关的工具函数,但语法上属于类命名空间。可通过类名或实例名调用(后者不推荐)。

参数传递:

☆实例方法隐式传递self(对象实例)。

☆类方法隐式传递cls(类本身)。

☆静态方法无隐式参数。

示例

☆Python实例方法:

class Animal:
    def __init__(self, name):
        # 初始化实例属性
        self.name = name
    
    def make_sound(self):
        """实例方法:返回动物的叫声(依赖对象实例)"""
        if self.name == "Dog":
            return "Woof!"
        elif self.name == "Cat":
            return "Meow!"
        return "Unknown sound"
    
    def show_info(self):
        """实例方法:显示动物信息"""
        return f"Animal: {self.name}, Sound: {self.make_sound()}"

# 创建实例
dog = Animal("Dog")
cat = Animal("Cat")
unknown_animal = Animal("Bird")

# 调用实例方法(通过对象名.方法名())
print(dog.make_sound())       # 输出:Woof!
print(cat.show_info())        # 输出:Animal: Cat, Sound: Meow!
print(unknown_animal.show_info())  # 输出:Animal: Bird, Sound: Unknown sound

self 类似 Java 的 this,隐式传递对象实例。

☆Python类方法:

class DateProcessor:
    # 类属性:存储日期格式
    date_format = "%Y-%m-%d"
    
    @classmethod
    def format_date(cls, year, month, day):
        """
        类方法:将年、月、日格式化为指定字符串
        cls:指向DateProcessor类本身
        """
        return f"{year}-{month:02d}-{day:02d}"
    
    @classmethod
    def parse_date(cls, date_str):
        """
        类方法:解析日期字符串为年、月、日元组
        """
        year, month, day = map(int, date_str.split('-'))
        return (year, month, day)

# 调用类方法(通过类名直接调用)
formatted = DateProcessor.format_date(2025, 6, 12)
print(formatted)  # 输出:2025-06-12

parsed = DateProcessor.parse_date("2025-06-12")
print(parsed)     # 输出:(2025, 6, 12)

# 类方法也可通过实例调用(但推荐用类名调用)
processor = DateProcessor()
print(processor.format_date(2025, 6, 13))  # 输出:2025-06-13

通过@classmethod定义,隐式传递cls参数。

☆Python静态方法:

class MathUtils:
    """数学工具类"""
    
    @staticmethod
    def is_prime(n):
        """判断一个数是否为质数(静态方法)"""
        if n <= 1:
            return False
        for i in range(2, int(n**0.5) + 1):
            if n % i == 0:
                return False
        return True
    
    @staticmethod
    def circle_area(radius):
        """计算圆的面积(静态方法)"""
        return 3.14159 * radius ** 2

# 通过类名直接调用(推荐方式)
print(MathUtils.is_prime(17))     # 输出: True
print(MathUtils.is_prime(15))     # 输出: False
print(MathUtils.circle_area(3))   # 输出: 28.27431

# 通过实例调用(可行但不推荐)
utils = MathUtils()
print(utils.circle_area(5))       # 输出: 78.53975

通过@staticmethod定义,不绑定到实例或类(即不会自动传递 self 或 cls),但它仍然定义在类的命名空间内。

区别小结

特点

函数

实例方法

类方法

静态方法

归属

独立

绑定到对象

绑定到类

属于类(不绑定)

隐式参数

self - 对象实例

cls - 类引用

调用方式

函数名

对象名.方法名()

类名.方法名() / 对象名.方法名()

类名.方法名() / 对象名.方法名() (后者不推荐)

其它

需@classmethod

需@staticmethod

其中,self和cls是强大的约定(PEP 8 推荐),self代表对象实例,cls代表类本身的引用”。@classmethod 和 @staticmethod 是装饰器,必须使用这些装饰器才能正确地定义类方法和静态方法。

附录

Python青少年简明教程:函数 https://blog.csdn.net/cnds123/article/details/141500961

Python青少年简明教程:类和对象入门 https://blog.csdn.net/cnds123/article/details/141953553

Python中的self参数介绍 https://blog.csdn.net/cnds123/article/details/148336578

Python中的变量、赋值及函数的参数传递概要https://blog.csdn.net/cnds123/article/details/148203255

python装饰器(Decorator)再谈 https://blog.csdn.net/cnds123/article/details/131234738

Python类的成员介绍  https://blog.csdn.net/cnds123/article/details/130898914

Python面向对象程序设计讲座 https://blog.csdn.net/cnds123/article/details/108354860

Python命名空间(Namespaces)和作用域(Scopes)讲座 https://blog.csdn.net/cnds123/article/details/108429084

Python嵌套函数(Nested function)和闭包(closure)https://blog.csdn.net/cnds123/article/details/129666657

你可能感兴趣的:(Python学习,编程实践系列,python,开发语言)