涛子 - 简单就是美

成单纯魁增,永继振国兴,克复宗清政,广开家必升

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

实例方法

class Human(object):
    def __init__(self, weight):
        self.weight = weight
   
    def get_weight(self):
        return self.weight

person = Human(45)
person.get_weight()
1. instance method 就是实例对象与函数的结合。
2. 使用类调用,第一个参数明确的传递过去一个实例。
3. 使用实例调用,调用的实例被作为第一个参数被隐含的传递过去。

类方法

class Human(object):
    weight = 12

    @classmethod
    def get_weight(cls):
        return cls.weight

Human.get_weight()
1. classmethod 是类对象与函数的结合。
2. 可以使用类和类的实例调用,但是都是将类作为隐含参数传递过去。
3. 使用类来调用 classmethod 可以避免将类实例化的开销。

静态方法

class Human(object):
    @staticmethod
    def add(a, b):
        return a + b

    def get_weight(self):
        return self.add(1, 2)

Human.add(1, 2)
Human().get_weight()
1. 当一个函数逻辑上属于一个类又不依赖与类的属性的时候,可以使用 staticmethod。
2. 使用 staticmethod 可以避免每次使用的时都会创建一个对象的开销。
3. staticmethod 可以使用类和类的实例调用。但是不依赖于类和类的实例的状态。
posted on 2015-08-26 17:12  北京涛子  阅读(217)  评论(0编辑  收藏  举报