zoukankan      html  css  js  c++  java
  • python的@classmethod和@staticmethod的区别和使用

    @classmethod

    classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

    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

    @staticmethod

    python staticmethod 返回函数的静态方法。

    class C(object):
        @staticmethod
        def f():
            print('runoob');
     
    C.f();          # 静态方法无需实例化
    cobj = C()
    cobj.f()        # 也可以实例化后调用

    输出结果如下

    runoob
    runoob
  • 相关阅读:
    模板语法
    django框架中登陆验证功能
    __call__
    JQuery基础
    JS中BOM和DOM操作
    Javascript基础
    css完结
    css深入
    css初识
    html深入解析
  • 原文地址:https://www.cnblogs.com/bt14/p/12147728.html
Copyright © 2011-2022 走看看