栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python类方法、静态方法和实例方法的使用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python类方法、静态方法和实例方法的使用

python中类的方法有三种,分别为:

  1. 类方法,通过装饰器@calssmethod进行修饰。
  2. 静态方法,通过装饰器@staticmethod进行修饰。
  3. 实例方法,属于方法类型的函数。

为什么要分为三种不同的方法呢?他们之间有什么区别和差异呢?首先这三种方法的可以获取类的属性和变量范围不同,具体区别如下:

  1. 类方法:不能获取构造函数定义的变量,可以获取类的属性。
  2. 静态方法:不能获取构造函数定义的变量,也不可以获取类的属性。
  3. 实例方法:既可以获取构造函数定义的变量,也可以获取类的属性值。

除了三种方法可以获取的类的属性存在差异,具体在方法本身被调用的方式上也有所差异,具体如下:

  1. 类方法:有两种调用方式,a.类名.类方法名     b.实例化调用
  2. 静态方法:有两种调用方式,a.类名.静态方法名    b.实例化调用
  3. 实例方法:见名知意,也许命名就是告诉大家,它只能通过实例化进行调用,事实也是。

基于以上理解,举个例子:

class FunctionTest:
    fun = "test"

    def __init__(self):
        self.__name = "function"
        self.__age = 2

    @classmethod
    def execute_class(cls):
        logging.info("this is class method!")

    @staticmethod
    def execute_static(x):
        logging.info("this is static method!")
        logging.info(f"{x} is a num.")

    def execute_normal(self):
        logging.info("This is normal method!")


if __name__ == '__main__':

    # 实例化调用
    FT = FunctionTest()
    # 只能通过实例化调用
    FT.execute_normal()
    # 实例化调用
    FT.execute_static(7)
    FT.execute_class()
    # 类.方法名 调用
    FunctionTest.execute_static(9)
    FunctionTest.execute_class()

执行结果如下:

2022-26-04 17:15:45:INFO:This is normal method!
2022-26-04 17:15:45:INFO:this is static method!
2022-26-04 17:15:45:INFO:7 is a num.
2022-26-04 17:15:45:INFO:this is class method!
2022-26-04 17:15:45:INFO:this is static method!
2022-26-04 17:15:45:INFO:9 is a num.
2022-26-04 17:15:45:INFO:this is class method!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/835521.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号