python类:类方法和静态方法

http://blog.csdn.net/pipisorry/article/details/49516185

面相对象程序设计中,类方法和静态方法是经常用到的两个术语。
逻辑上讲:类方法是只能由类名调用;静态方法可以由类名或对象名进行调用。
在C++中,静态方法与类方法逻辑上是等价的,只有一个概念,不会混淆。
在python中,方法分为三类实例方法、类方法、静态方法。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = 'python实例方法,类方法和静态方法区别及使用'
__author__ = '皮'
__email__ = '[email protected]'
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
"""
import traceback


class T:
    def InstanceMethod(self):
        print("instance Method!")
        print(self)

    @classmethod
    def ClassMethod(cls):
        # def ClassMethod(self):#当然这样也不会出错
        print("class Method")
        print(cls)

    @staticmethod
    def StaticMethod():
        print("static method")


t = T()

t.InstanceMethod()
t.ClassMethod()
t.StaticMethod()

T.ClassMethod()
T.StaticMethod()

T.InstanceMethod(t)

# 错误的情况
try:
    t.ClassMethod(T)
    T.InstanceMethod()
except:
    print(traceback.format_exc())
在python中,两种方法的主要区别在于参数
实例方法隐含的参数为类实例self;
类方法隐含的参数为类本身cls;
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。

逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。
而实际上,python实现了一定的灵活性使得类方法和静态方法都能够被实例和类二者调用。

from:http://blog.csdn.net/pipisorry/article/details/49516185

ref:python类:class


你可能感兴趣的:(python,静态方法,类方法)