python 实例方法,类方法,静态方法

it2022-05-05  191

python 实例方法,类方法,静态方法

实例方法

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 北京涛子 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/liujitao79/p/4761048.html


最新回复(0)