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()
  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    2.5.3 表单过滤器
    2.5.2 子过滤器
    2.5.1 位置过滤器:
    2.4 通过属性来选择元素
    2.3 根据层级查找元素
    2.2.4 元素选择器
    2.2.3 Class选择器
    2.2.2 ID选择器
  • 原文地址:https://www.cnblogs.com/ltyc/p/14607128.html
Copyright © 2011-2022 走看看