zoukankan      html  css  js  c++  java
  • 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 可以使用类和类的实例调用。但是不依赖于类和类的实例的状态。
    
  • 相关阅读:
    网络和笔记本
    病毒惹的祸
    Virtual MachineVmware(2)
    VS2010 工具箱装载出错
    Virtual Machine VmWare(1)
    javascript写计数器
    代码自动生成操作
    用live writer写博客
    上海招聘.net程序员
    将用户导入到membership
  • 原文地址:https://www.cnblogs.com/liujitao79/p/4761048.html
Copyright © 2011-2022 走看看