类的方法
- 公有方法
- 私有方法
- 类方法
- 静态方法
def methodName(self [,arg1, ...]) :
statements
- 调用
instance.methodName()
def __methodName(self [,arg1, ...]) :
statements
- 调用
类定义时调用.
- 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()
- staticmethod(function) -> static method
4.1 装饰器
- 定义
@staticmethod
def methodName() :
statements
- 调用
className.methodName()
4.2 staticmethod(function)
def methodName() :
statements
newMethodName = staticmethod(methodName)
- 调用
className.newMethodName()
- 公有方法
- 私有方法
- 类方法
- 静态方法
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()