1. 类方法

是类对象所拥有的方法,需要用修饰器@classmethod来标识其为类方法,对于类方法,第一个参数必须是类对象,一般以cls作为第一个参数(当然可以用其他名称的变量作为其第一个参数,但是大部分人都习惯以'cls'作为第一个参数的名字,就最好用'cls'了),能够通过实例对象和类对象去访问。

class people:
country = 'china' #类方法,用classmethod来进行修饰
@classmethod
def getCountry(cls):
return cls.country p = people()
print p.getCountry() #可以用过实例对象引用
print people.getCountry() #可以通过类对象引用

类方法还有一个用途就是可以对类属性进行修改:

class people:
country = 'china' #类方法,用classmethod来进行修饰
@classmethod
def getCountry(cls):
return cls.country @classmethod
def setCountry(cls,country):
cls.country = country p = people()
print p.getCountry() #可以用过实例对象引用
print people.getCountry() #可以通过类对象引用 p.setCountry('japan') print p.getCountry()
print people.getCountry()

结果显示在用类方法对类属性修改之后,通过类对象和实例对象访问都发生了改变

2. 静态方法

需要通过修饰器@staticmethod来进行修饰,静态方法不需要多定义参数

class people:
country = 'china' @staticmethod
#静态方法
def getCountry():
return people.country print people.getCountry()

总结

从类方法和实例方法以及静态方法的定义形式就可以看出来,类方法的第一个参数是类对象cls,那么通过cls引用的必定是类对象的属性和方法;而实例方法的第一个参数是实例对象self,那么通过self引用的可能是类属性、也有可能是实例属性(这个需要具体分析),不过在存在相同名称的类属性和实例属性的情况下,实例属性优先级更高。静态方法中不需要额外定义参数,因此在静态方法中引用类属性的话,必须通过类对象来引用

最新文章

  1. UDS(ISO14229-2006) 汉译(No.4 术语和缩写)
  2. DigitalOcean上SSH Key的创建(附DigitalOcean邀请)
  3. UVa 10054,欧拉回路
  4. C++中 _itoa_s方法简介
  5. CRT detected that the application wrote to memory after end of heap buffer.
  6. Django之模型管理器filter处理问题
  7. 友盟分享到微信 监听不执行 监听只执行onStart,(onResult,onError,onCancel 不执行)
  8. OSChinaclient源代码学习(1)--Android与Server的交互
  9. oracle01
  10. python 函数“四剑客”的使用和介绍
  11. spring 中的设计模式
  12. servlet中将值以json格式传入
  13. [原][算法][earth]三段smooth,传入时间,返回距离。仿谷歌视角飞跃处理
  14. session_unset,session_destroy
  15. dns隧道 dns2tcpd
  16. perl 中的引用
  17. mysql多列索引优化
  18. 《A_Pancers》团队作业6—团队项目系统设计改进与详细设计
  19. FPGA/SOPC学习转载
  20. HDU 2114 Calculate S(n)

热门文章

  1. Android物联网应用程序开发(智慧园区)—— 图片预览界面
  2. openmesh - src - trimesh delete and add elements
  3. 使用.NET 6开发TodoList应用(21)——实现API版本控制
  4. python + pytest + allure生成测试报告
  5. centOS8安装java14
  6. 新建koa2项目
  7. react中实现css动画
  8. 聊聊docker那些端口问题
  9. CentOS6.5安装CM5.13
  10. vue-json-editor可视化编辑器的介绍与应用