新闻动态

python基础之类方法和静态方法

发布日期:2021-12-20 21:55 | 文章来源:源码之家

类方法

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())  #无必要 直接使用静态方法 输出仍是导入时间




复习


总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注本站的更多内容!

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部