0

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.

Here's an explanation. Say I have the variable foo and I want it to always be equal to bar plus three.

If I do

bar = 6
foo = bar+3

Then foo is equal to 9. But if I then do

bar = 5

Then foo is still 9. I'd like foo to be equal to 8, without executing

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.

3
  • 4
    It's not possible to + 3 without executing + 3. You can hide it behind a class (look up object-oriented programming), but you will still be executing the same logic. Commented Jan 5, 2019 at 2:25
  • That sounds more like a function. Commented Jan 5, 2019 at 2:32
  • If you think the answers answer your question, please consider accepting the one that you think is the best by clicking on that checkmark. Commented Jan 6, 2019 at 9:26

3 Answers 3

1

foo can be defined like this:

foo = lambda: bar + 3

And can be used like this:

print(foo())

As you can see, foo is no longer a variable. foo is a function. foo can't be a variable because a variable doesn't suddenly change its value just because some other variable's value changed.

Sign up to request clarification or add additional context in comments.

Comments

1

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."

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

Comments

-1

I think you can use an object-oriented method to define Bar and Foo in the same class. If you want to get the value of foo, call the method in the class to perform foo = bar+3. I don't know if I can help you. I am a rookie.

1 Comment

Welcome to Stack Overflow. If you're uncertain of the quality of your answer or your ability to respond in a worthwhile way, please refrain from responding. After you earn 50 points reputation, consider writing a comment in response to the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.