Question when adding conditions including external functions to function parameters.

Asked 2 years ago, Updated 2 years ago, 56 views

Python function question. For example, an external function a returns the current temperature In creating a function b that operates according to temperature,

def b (c = True):
    while true:
        if c:
            Turn on the air conditioner.
        else:
            Turn off the air conditioner.

b( a() > 30 )

When I made it, When executing a function as shown above If you add a() > 30 to the c parameter, When the function is operated, it continuously calls the a() function to the return value at the time of execution without updating the situation The parameters become fixed. I think it's a natural result, but...

You change the conditions to temperature, or humidity, and you transfer the conditions to the parameters I want to keep the conditions of the external function updated within function b when the function is executed How should I pass it on to the parameter? Or is there any other way? I wonder if I can solve this problem by putting conditions in the parameters.

python function

2022-09-19 23:26

1 Answers

It's a structure where functions and conditions can be changed, but I understood it in a form that can be checked within the function.

To make it as simple as possible,

class B:
    def __init__(self, func, greater_than=None, less_than=None):
        self.func = func
        self.greater_than = greater_than
        self.less_than = less_than

    def _check_greater_than(data):
        if self.greater_than:
            return data > self.greater_than
        return True

    def _check_less_than(data):
        if self.less_than:
            return data < self.less_than
        return True

    def loop(self):
        while True:
            result = self.func()
            if self._check_greater_than(result) and self._check_less_than():
                print ("turn on the air conditioner")
            else:
                print ("Turn off the air conditioner")

b = B(a, greater_than=30)
b.loop()

I'm thinking about doing it like this

Put the function you want into func without running it For greater_than, the value shown in func should be greater than any value (required X),
For less_than, the value shown in func should be less than any value (required X)

If you put it in like this, it will be automatically calculated.


2022-09-19 23:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.