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

python笔记29 类方法和静态方法

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

python笔记29 类方法和静态方法

类方法

class People:
    country='China'
    # 类方法 用classmethod来修饰
    @classmethod  #通过标识符来表示下方方法为类方法
    def get_country(cls):  #习惯性使用cls
        return cls.country  #访问类属性
        pass
    pass
print(People.get_country())  #通过类对象去引用
p=People()
print('实例对象访问%s'%p.get_country())  #通过实例对象去访问

class People:
    country='China'
    # 类方法 用classmethod来修饰
    @classmethod  #通过标识符来表示下方方法为类方法
    def get_country(cls):  #习惯性使用cls
        return cls.country  #访问类属性
        pass
    @classmethod
    def change_country(cls,data):
        cls.country=data  #修改类属性的值在类方法中
    pass
print(People.get_country())  #通过类对象去引用
p=People()
print('实例对象访问%s'%p.get_country())
People.change_country('英')
print(People.get_country())

静态方法

class People:
    country='China'
    # 类方法 用classmethod来修饰
    @classmethod  #通过标识符来表示下方方法为类方法
    def get_country(cls):  #习惯性使用cls
        return cls.country  #访问类属性
        pass
    @classmethod
    def change_country(cls,data):
        cls.country=data  #修改类属性的值在类方法中
    pass
    @staticmethod
    def getData():  #无需传参数
        return People.country
    pass
print(People.getData())   #可以访问


# print(People.get_country())  #通过类对象去引用
p=People()
print(People.getData())   #可以访问  注意 一般情况下 我们不会通过实例对象去访问静态方法

为什么要使用静态方法呢?
由于静态方法主要来存放逻辑性的代码 本身和类以及实例对象没有交互
也就是说 在静态方法中 不会涉及到类中方法和属性的操作
数据资源能够得到有效的充分利用

# demo 返回当前的系统时间
import time #引入时间模块
class TimeTest:
    def __init__(self,hour,min,second):
        self.hour=hour
        self.min=min
        self.second=second

    @staticmethod  #直接定义为静态方法 不需要实例属性
    def showtime():
        return time.strftime('%H:%M:%S',time.localtime())
    pass
print(TimeTest.showtime())
t=TimeTest(2,10,15)
print(t.showtime())  #无必要 直接使用静态方法 输出仍是导入时间




复习


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

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

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