python类变量,类方法,静态方法

一、class object、class variable

首先class在python里面是一个对象,它有独立区域存储属于自己的数据,而不需要实例化。

 

class Hehe(object):
     
    count = 0 # class variable
     
    def __init__(self, c):
        Hehe.count = Hehe.count + c
         
        
        print 'addres same' if id(Hehe.count) == id(self.count) else 'addres not same'
        #addres same
         
        self.count = self.count + c # instance variable
         
        print 'addres same' if id(Hehe.count) == id(self.count) else 'addres not same'
        #addres not same

        print 'class var: %d' %Hehe.count
        print 'instance var: %d' %self.count

     
h1 = Hehe(1)
print ''
h2 = Hehe(10)

输出:
addres same
addres not same
class var: 1
instance var: 2

addres same
addres not same
class var: 11
instance var: 21

 

 结论:

  1. instance 变量未赋值前value为class 变量地址是一样的,赋值后,地址发生变更,这说明class变量与instance变量是两个引用
  2. instance 变量生存范围在instance层级,class变量生存在class 对象里

二、@classmethod和@staticmethod

 

class Hehe(object):
     
    count = 0 # class variable
     
    def __init__(self, c):
        Hehe.count = Hehe.count + c
        self.count = self.count + c # instance variable
                  
    @classmethod
    def get_class_count(cls_obj):
        return cls_obj.count

    @staticmethod
    def a_static_method():
        pass
h1 = Hehe(1)
 
# class level
print h1.get_class_count()
# 11
print h1.count
# 2
 
# instance level
print Hehe.get_class_count()
# 11
print Hehe.count
# 11

结论:

  1. @classmethod标记的方法可以通过class直接调用,因为第一个参数包含class object,所以可以拿到class variable
  2. @staticmethod和@classmethod都可以被class直接调用,但@staticmethod拿到不到class object

贴个stackflow的图片:

http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner



 

 

 

 -end 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值