zoukankan      html  css  js  c++  java
  • Python Classmethod和Staticmethod函数

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

    class Animal:
        #属性默认为类属性(可以直接被类本身调用)
        nums = 10
    
        #实例化方法,必须要实例化类就可以被类调用
        def cat(self):
            print('------ cat --------------')
            print(self) #self:表示实例化类后的地址id
            print(self.nums)
        
        #类方法,不用实例化类就可以被类调用
        @classmethod 
        def dog(cls):
            print('--------- dog ---------------')
            print(cls) #表示没有被类实例化后的类本身
            print(cls.nums)
        
        #不传递默认self参数的方法(该方法可以直接被类调用,但是不标准)
        def pig():
            print('------------ pig ---------------')
            print()
    
    
    obj = Animal()
    obj.cat()
    Animal.dog()
    Animal.pig()

    执行结果:

    2.Staticmethod描述:Python staticmethod返回函数的静态方法

    该方法不强制要求传递参数,如下声明一个静态方法

    class Solution:
        
        nums = 1
    
        @staticmethod 
        def test1():
            print('------ test1 ---------')
            return 'test1'
    
        @staticmethod 
        def test2(name):
            print('------ test2 ---------')
            print(name)
            return 'test2'
    
    print(Solution.test1())
    print(Solution.test2('alex'))

    执行结果:

  • 相关阅读:
    st-load视频性能测试
    gitlab-ci集成SonarQube代码质量检查
    退役记
    洛谷 P5195 【[USACO05DEC]Knights of Ni S】
    洛谷 P4742 【[Wind Festival]Running In The Sky】
    洛谷 SP13105 【MUTDNA
    洛谷 P3174 【[HAOI2009]毛毛虫】
    洛谷 P1542 【包裹快递】
    Python函数的返回值
    ubuntu18.04修改国内apt源
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13846210.html
Copyright © 2011-2022 走看看