简体   繁体   English

如何在 Python 中更新变量中的值?

[英]How can I update an value in a variable in Python?

I'm hoping to make a variable that changes when a value "in it" changes.我希望制作一个变量,当“其中”的值发生变化时,该变量会发生变化。 That may sound confusing.这听起来可能令人困惑。

I'm new to Python, and I'm hoping to use this in future projects.我是 Python 新手,我希望在未来的项目中使用它。

Here's an explanation.这是一个解释。 Say I have the variable foo and I want it to always be equal to bar plus three.假设我有变量foo并且我希望它总是等于bar加三。

If I do如果我做

bar = 6
foo = bar+3

Then foo is equal to 9. But if I then do那么foo等于 9. 但是如果我那么做

bar = 5

Then foo is still 9. I'd like foo to be equal to 8, without executing然后 foo 仍然是 9。我希望 foo 等于 8,而不执行

foo = bar+3

again.再次。 Is there anything I can do to make that happen?有什么我可以做的吗?

Thanks.谢谢。

EDIT: Thanks for the answers!编辑:感谢您的回答! I was already aware about how variables work.我已经知道变量是如何工作的。 I guess using functions with return is the only way to do it.我想使用带return函数是唯一的方法。

foo can be defined like this: foo可以这样定义:

foo = lambda: bar + 3

And can be used like this: 可以这样使用:

print(foo())

As you can see, foo is no longer a variable. 如您所见, foo不再是变量。 foo is a function. foo是一个函数。 foo can't be a variable because a variable doesn't suddenly change its value just because some other variable's value changed. foo不能是变量,因为一个变量不会仅仅因为其他变量的值改变而突然改变其值。

When you type 当您键入

foo = bar + 3

It does not mean " foo is equal to three more than the value of bar ", it means " foo is equal to three more than the value of bar RIGHT NOW ." 这并不意味着“ foobar的值大三”,而是“ foo等于bar RIGHT的值大三”。

If you need to do the former, you'll need to do some trickery. 如果需要使用前者,则需要进行一些欺骗。

class DelayedAdditionContext(object):
    def __init__(self, bar=0):
        self.bar = bar

    @property
    def foo(self):
        return self.bar + 3

context = DelayedAdditionContext()
context.bar = 5
context.foo  # 8
context.bar = 8
context.foo  # 11

but really this is just making a function under the hood. 但这实际上只是在发挥作用。

def calculate_foo(bar):
    return bar + 3

bar = 5
foo = calculate_foo(bar)  # 8

bar = 8
foo = calculate_foo(bar)  # 11

Define a function to do this: 定义一个函数来做到这一点:

bar = 6
foo = bar + 3
# bar = 6, foo = 9

def set_bar(v):
    global bar, foo
    bar = v
    foo = bar + 3

set_bar(5)
# bar = 5, foo = 8

There is no general way to monitor variables in real time as I know. 据我所知,没有通用的实时监视变量的方法。

Please see this post (object-oriented programmatically). 请参阅这篇文章 (以编程方式面向对象)。

EDIT 编辑


To achieve this, you need to define your own type (that extended). 为此,您需要定义自己的类型(扩展的类型)。

I think you can use an object-oriented method to define Bar and Foo in the same class. 我认为您可以使用面向对象的方法在同一类中定义Bar和Foo。 If you want to get the value of foo, call the method in the class to perform foo = bar+3. 如果要获取foo的值,请调用类中的方法以执行foo = bar + 3。 I don't know if I can help you. 我不知道能不能帮您。 I am a rookie. 我是新秀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM