zoukankan      html  css  js  c++  java
  • Python中的实例方法、classmethod和staticmethod的区别

    class NewsPaper(object):
    
        # 类属性
        __print_times = 0 # 下划线表示私有属性
    
        # 实例方法
        def __init__(self, title, content):
            self.title = title  # 实例属性
            self.content = content  # 实例属性
            # 累加类属性变量
            NewsPaper.__print_times += 1
    
        # 实例方法
        def show_news(self):
            print("报纸标题:%s" % self.title)
            print("报纸内容:%s" % self.content)
    
        # 类方法(封装类属性,外界提供访问接口,保护类属性)
        @classmethod
        def get_times(cls):
            return cls.__print_times
    
        # 静态方法
        @staticmethod
        def static_method():
            # 静态方法(可通过类名访问类属性)
            # 静态方法不可访问实例属性
            print(NewsPaper.__print_times)
            print("我是静态方法!")

    1. 实例属性和实例方法

    在类中使用__init__初始化的属性叫做叫做实例属性

    使用def定义的函数叫做实例方法

    2. 类属性和类方法

    在创建类class下面直接定义的变量称作类属性

    使用@classmethod装饰器进行装饰的函数,称作类方法 

        # 类方法(封装类属性,外界提供访问接口,保护类属性)
        @classmethod
        def get_times(cls):
            return cls.__print_times

    3. 静态方法

    使用@staticmethod装饰器进行装饰的函数,称作静态方法

    静态方法没有默认的 self 或者 cls 参数, 如果方法并没有访问实例属性或者类属性, 我们可将其设置为静态方法, 减少了参数的传递.

        # 静态方法
        @staticmethod
        def static_method():
            # 静态方法(可通过类名访问类属性)
            # 静态方法不可访问实例属性
            print(NewsPaper.__print_times)
            print("我是静态方法!")

     三者的区别

    实例方法:实例方法可以通过实例对象进行调用和访问, 方法内可以使用self访问调用实例属性和实例方法,使用cls关键字访问调用类属性和类方法,

    类方法: 类属性和类方法归所有本类型的实例对象共享, 可通过实例对象访问, 也可通过类对象访问. 如果要修改类属性, 必须通过类名的方式访问.

    静态方法:静态方法可通过类对象或者实例对象访问, 静态方法内部不可访问实例属性, 但可通过类名访问实例属性.

  • 相关阅读:
    H3C ER6300 + 两台 H3C S5120 组网举例
    H3C S5120-52P-WiNet交换机配置
    H3C S5120清除console口密码
    光纤简介
    Windows server 2008 R2 多用户远程桌面
    AutoIt 软件自动化操作
    windows server 2008 R2 计划任务备份系统
    AD域部署使用bginfo软件
    使用WSL吧
    Could not load file or assembly……
  • 原文地址:https://www.cnblogs.com/yanguhung/p/10145763.html
Copyright © 2011-2022 走看看