简体   繁体   English

确保变量在任何给定时间仅处于一种状态

[英]Ensure a variable is only at one state at any given time

Let's say we have a simulation of taxi movements. 假设我们模拟了出租车的运动。 Each car at any given time, can be only in one of idle, rebalancing, serving states (just as an example, there are many more in my simulation). 在任何给定时间,每辆汽车只能处于idle, rebalancing, serving状态之一(仅作为示例,在我的模拟中还有更多)。 At any time, I have to check the state of each of the vehicles and act accordingly. 在任何时候,我都必须检查每辆车的状态并采取相应的措施。 For example, if a vehicle was idle and then picked up a passenger, its state should change from idle to serving . 例如,如果车辆闲置然后接载乘客,则其状态应从idle更改为serving Importantly, at any given time the vehicle can only be in one of those states and its action set is also dependent on that state. 重要的是,在任何给定时间,车辆只能处于那些状态之一,并且其动作集也取决于该状态。

Currently, I am doing this with a long list of if-else checks, but feels very naive and it's very difficult to debug. 目前,我使用一长串if-else检查来执行此操作,但是感觉很幼稚并且很难调试。 For example, the main logic checks the state of a car first: 例如,主要逻辑首先检查汽车的状态:

    if self.should_move():


        _ = _make_a_decision(t)
        self.update_rebalancing(WARMUP_PHASE)



    if self.is_busy():
        self.keep_serving()

    elif self.is_waiting_to_be_matched():
        # it's sitting somewhere
        self.keep_waiting()




    elif self.rebalancing:  # and not self.busy:
        self.update_rebalancing(WARMUP_PHASE)

Then any of those functions update its state accordingly, all including statements like this 然后,这些功能中的任何一个都会相应地更新其状态,所有这些都包括这样的语句

    self.idle = False
    self.rebalancing = False
    self.serving = True
    self.time_idled = 0

There is a lot of repetition and easy to make mistakes. 重复很多,容易出错。

I am wondering if 我想知道

  1. there is a programming pattern for this situation 有这种情况的编程模式
  2. If Python specifically has functionalities to handle this case 如果Python特别具有处理这种情况的功能

This is a really broad question and there's not any correct answer to it.. 这是一个非常广泛的问题,没有正确的答案。

But to try to help, why not use a class? 但是要尝试提供帮助,为什么不使用课程呢?

class Taxi:
    # One variable to hold an enum of the states.
    self.state = 'idle'

    # function to update the state
    def setState(self, state):
        self.state = state

    # Functions to check the state (could have one to get the state and check later
    def isIdle(self):
        return self.state == 'idle' 

Then any functionality the taxi needs to do can be put in the class like: 然后,出租车需要执行的任何功能都可以放入此类中:

    def pickupPassengers():
        if self.state != 'idle':
            return

        self.passengers += 1

Then you create your taxis and manage them through the class 然后,您创建出租车并通过课程进行管理

taxi1 = Taxi()
taxi1.getPassengers()

There are a few ways to accomplish what you want. 有几种方法可以实现您想要的。 Since it can get confusing if you have to manually change multiple variables every time you have a state change... just have one variable in charge of the state! 如果每次必须更改状态时都必须手动更改多个变量,可能会引起混乱,因此,只需一个变量来管理状态! If you want to still be able to refer to Taxi.idle , Taxi.rebalancing , etc, then you can create @property methods. 如果仍然希望引用Taxi.idleTaxi.rebalancing等,则可以创建@property方法。 They look like functions when you define them but are called like properties. 当您定义它们时,它们看起来像函数,但被称为属性。

See the example below for a Taxi class which has only one state variable, self._state and uses @property methods to return the status. 请参阅下面的例子Taxi它只有一个状态变量,类self._state并使用@property的方法来恢复状态。

class Taxi:
    def __init__(self, initial_state = "idle"):
        self._state = initial_state


    @property
    def idle(self):
        return self._state == "idle"

    @property
    def rebalancing(self):
        return self._state == "rebalancing"

    @property
    def serving(self):
        return self._state == "serving"

    def serve(self):
        print("\nChanging state to serving\n")
        self._state = "serving"

T = Taxi() # Initialize taxi

print(f"Taxi is idle: {T.idle}")
print(f"Taxi is rebalancing: {T.rebalancing}")
print(f"Taxi is serving: {T.serving}")

T.serve()

print(f"Taxi is idle: {T.idle}")
print(f"Taxi is rebalancing: {T.rebalancing}")
print(f"Taxi is serving: {T.serving}")```
Output:

Taxi is idle: True
Taxi is rebalancing: False
Taxi is serving: False

Changing state to serving

Taxi is idle: False
Taxi is rebalancing: False
Taxi is serving: True

Your design problem is that you're trying to use a series of Booleans to embody one-hot encoding of a discrete variable (state). 您的设计问题是,您试图使用一系列布尔值来体现离散变量(状态)的一次性编码。 If you want only one value at a time, the natural way to do this is with a single variable. 如果一次只需要一个值,那么自然的方法就是使用单个变量。 Enumeration types are what most advanced languages use for this. 枚举类型是大多数高级语言用于此目的的类型。 For instance, you can encode "idle" as 0, "rebalancing" as 1, etc. 例如,您可以将“ idle”编码为0,将“ rebalance”编码为1,等等。

Python code would look something like this: Python代码如下所示:

from enum import Enum, unique, auto    

@unique
class TaxiState(Enum):

    IDLE  = auto()
    REBAL = auto()
    SERVE = auto()


class Taxi():

    def __init__(self):
        self.state = TaxiState.IDLE 

    def is_busy(self):
        return self.state != TaxiState.IDLE

You don't worry about the coding; 您不必担心编码。 auto handles that. auto处理。 All you do is use the enumeration name as a value. 您要做的就是将枚举名称用作值。 You get to code just as you designed that aspect of the model. 您可以像设计模型的该方面一样进行编码。

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

相关问题 如何确保cron作业在任何时间仅在一台主机上运行 - How can I ensure cron job runs only on one host at any time 如何确保一次仅运行一个线程,最新的数据? - How to ensure only one thread runs at a time, the most recent data? 仅获取在熊猫中给定年份的任何一年重复的数据 - Get only data that are repeated any one of the given year in pandas python:总有一次只能初始化一个变量吗? - python: is there anyway to initialize a variable only one time? Python中如何保证一段代码一次只能被一个请求执行? - How to ensure that a block of code can be executed only by one request at a time in Python? 如果只给出一个参数,如何忽略变量声明中的第二个参数 - How to ignore a second parameter in a variable declaration if only one is given 确保只运行一个类的一个实例 - Ensure that only one instance of a class gets run wxPython:确保只打开一个面板的一个实例 - wxPython: Ensure only one instance of a panel is open 在任何给定时间终止循环 - Terminate loop at any given time Python tkinter:如何确保在单击时仅创建一个子窗口,而不在每次单击按钮时创建一个新窗口? - Python tkinter: How can I ensure only ONE child window is created onclick and not a new window every time the button is clicked?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM