美文网首页过程测试开发
python_类方法的调用

python_类方法的调用

作者: 古佛青灯度流年 | 来源:发表于2016-07-29 10:47 被阅读234次
    python.png
    • for Python 2.7.X
    • 实例方法调用

      clss A:
          def b(self):
                print 'abc'
      c = a()
      c.b()
      

    这种调用方法,在调用类时,必须先将类实例化,然后才能调用类中方法,这种调用比较麻烦

    • 静态方法调用

      clss A:
          @staticmethod
          def b(self):
                print 'abc'
      a.b()
      

    这种调用方法,不需要实例化,用起来很方便

    • 类方法调用

      clss A:
          @classmethod
          def b(self):
                print 'abc'
      a.b()
      

    这种调用方法,与@staticmethod(静态方法)用法一致,但是存在细微区别,一张图片了解区别:

    • @classmethod与@staticmethod的区别:

      class Kls(object):
           def __init__(self, data): 
                self.data = data 
          def printd(self): 
                print(self.data) 
          @staticmethod 
          def smethod(*arg): 
                print('Static:', arg) 
          @classmethod 
          def cmethod(*arg): 
                print('Class:', arg)
      ik = Kls()
      

    执行顺序:

    区别.jpg
    • 总结:从上图可以看出,使用函数修饰符@classmethod与@staticmethod后,直接用类调用方法运行起来都是一样的;区别是类实例化后,添加@staticmethod的方法是不能用实例化调用方法的;
      注意:如果想用类直接调用方法,需要在每个方法上方添加 函数修饰符

    以上参考前辈文章总结而来,若有不全,请指教。随时补充

    @雾霾--2016-07-29 10:47:49

    相关文章

      网友评论

        本文标题:python_类方法的调用

        本文链接:https://www.haomeiwen.com/subject/jjczjttx.html