23-python_类的方法

类的方法
 - 公有方法 
 - 私有方法
 - 类方法
 - 静态方法

1 公有方法

  - 定义
    def methodName(self [,arg1, ...]) :
        statements
  - 调用
    instance.methodName()

2 私有方法

  - 定义
    def __methodName(self [,arg1, ...]) :
        statements
  - 调用
    类定义时调用.

3 类方法

   - 装饰器 @classmethod
   - classmethod(function) -> class method

 3.1 装饰器
   - 定义 
    @classmethod
    def methodName(self) :
        statements
 
   - 调用
    className.methodName()

 3.2 classmethod(function)
   - 定义 
    def methodName(self) :
        statements
    newMethodName = classmethod(methodName)

   - 调用
    className.newMethodName()

4 静态方法

   - 装饰器 @staticmethod
   - staticmethod(function) -> static method

 4.1 装饰器
   - 定义
    @staticmethod
    def methodName() :
        statements

   - 调用
    className.methodName()

 4.2 staticmethod(function)
    def methodName() :
        statements
    newMethodName = staticmethod(methodName)

   - 调用
    className.newMethodName()
 

5 完整例子

class Methods :

    name = "hello"
    
    def func1(self) :
        print self.name, "func1 is public method"

    def __func2(self) :
        print self.name, "__func2 is private method"        
#######################################################

    def classFunc3(self) :
        print self.name, "classFunc3 is class method"

    @classmethod
    def classFunc3_2(self) :
        print self.name, "classFunc3_2 is class method"

    classFunc3_3 = classmethod(classFunc3)
#######################################################

    def staticFunc4() :
        print "staticFunc4 is static method"

    @staticmethod
    def staticFunc4_2() :
        print "staticFunc4_2 is static method"

    staticFunc4_3 = staticmethod(staticFunc4)


if __name__ == "__main__" :

    instance = Methods()

    # call public method
    instance.func1()
    # call private method
    try :
        instance.__func2()
    except AttributeError, msg :
        print "call private failed!!!!!!!", msg

    try :            
        Methods.classFunc3()
    except TypeError, msg:
        print msg

    Methods.classFunc3_2()        
    Methods.classFunc3_3()
    

    Methods.staticFunc4_2()
    Methods.staticFunc4_3()




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值