zoukankan      html  css  js  c++  java
  • 类与缓存问题 类与属性的关系

    前情提要:

      当我们需要从redis缓存中直接拿数据,且所拿的数据定义在要一个类中,是类的一个属性,我们需要在其他类中,或者其他地方使用这个属性 ,当redis中的数据发生变化时,

      类中的属性并不会随着redis中数值的改变而改变。因为类在生成的时候,他的属性就已经固定了,不会更改。所以不管redis中的值如何变化。类的属性是不变的。

    x = 100
    
    class ppp():
        
        run = x
    
    
    class Test:
    
        def __init__(self):
            pass
    
        sc = ppp()
    
        def ceshi(self):
            if ppp.run > 10:
                print(ppp.run)
                return
            else:
                print('我比你小,我是%s' % ppp.run)
                return
    
    
    A = Test()
    A.ceshi()
    
    x = 10
    B = Test()
    B.ceshi()

    解决方法,将类的属性变成一个函数,并且加上property装饰器,这时你在其他类中通过这个类所获得(通过.获得)的是函数的返回值,而不是该类的属性,每次调用都会运行该函数,去内存中重新拿值进行,运算赋值。

    x = 100
    
    
    class ppp():
    
        # run = x
        @property
        def run(self) -> int:
            return x
    
    
    class Test:
    
        def __init__(self):
            pass
    
        sc = ppp()
    
        def ceshi(self):
            if self.sc.run > 10:
                print(self.sc.run)
                return
            else:
                print(self.sc.run)
                return
    
    
    A = Test()
    A.ceshi()
    
    x = 10
    B = Test()
    B.ceshi()
  • 相关阅读:
    javascript运行机制
    ios-scroll 和系统设置overflowscroll后卡顿
    input属性autocomplate背景颜色
    img 的onload事件和complate事件区别
    image图片之间缝隙bug解决方法
    gulp使用指南
    getQueryString
    decodeURI()和decodeURIComponent()函数
    css样式实现水平方向滚动
    I2C
  • 原文地址:https://www.cnblogs.com/ltyc/p/14607128.html
Copyright © 2011-2022 走看看