3.Python语法-classmethod

classmethod 修饰符

与self类不同,不需实例化

  • 函数不需要实例化,不需要 self 参数
  • 需填写cls 参数
    - 调用类的属性,类的方法,实例化对象等
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A(object):
    bar = 1
    def func1(self):  
        print ('foo') 
    @classmethod
    def func2(cls):
        print ('func2')
        print (cls.bar)
        cls().func1()   # 调用 foo 方法
 
A().func2()               # 不需要实例化

输出:

func2
1
foo
posted @ 2021-01-27 13:15  鲁哒哒  阅读(145)  评论(0编辑  收藏  举报