簡體   English   中英

正確說明狀態槽功能

[英]Proper way to state a condition trough functions

我有一個具有不同功能的代碼。 在其中一個內部有一個條件。 我必須檢查是否發生這種情況才能執行另一個功能。

這樣做的正確方法是什么? 我已經嘗試過類似的方法,但是沒有用

例:

class MyClass:
    def thisFunction(self):
        try: 
            "I'm doing things"
        except:
            self.stop = print("That's already done!")
    def thisOtherFunction(self):
        "I'm doing things with things done in thisFunction"
s = MyClass()
s.thisFunction()
if self.stop == None:
    s.thisOtherFunction()
else:
    pass

非常感謝!

更新

實際上,這樣做要簡單得多:

class MyClass:
    def thisFunction(self):
        try: 
            "I'm doing things"
        except:
            self.stop = print("That's already done!")
   def thisOtherFunction(self):
        try:
            "I'm doing things with things done in thisFunction"
        except:
            pass
s = myClass()
s.thisFunction()
s.thisOtherFunction()

多虧了亞當·史密斯(Adam Smiths)的榜樣,我根本沒有考慮過。 不過,也許不是那么優雅。

Update2的另一種方法是以這種方式使用def __init__

    class MyClass:
        def __init__(self):
             self.commandStop = False
        def thisFunction(self):
            try: 
                "I'm doing things"
            except:
                self.commandStop = True
        def thisOtherFunction(self):
            "I'm doing things with things done in thisFunction"
        def conditionToGo(self):
             if self.commandStop == False:
                 print("That's already done!")
             else:
                 s.thisOtherFunction()
s = myClass()
s.thisFunction()
s.conditionToGo()

我必須先進行模式轉換,然后才能對值進行一系列轉換,並且每次都需要通過測試。 您可以使用以下方法構造它:

def pipeline(predicate, transformers):
    def wrapped(value):
        for transformer in transformers:
            value = transformer(value)
            if not predicate(value):
                raise ValueError(f"{value} no longer satisfies the specified predicate.") 
        return value
    return wrapped

然后,舉一個例子,假設我需要對一個數字做一些數學運算,但要確保該數字永遠不會變為負數。

operations = [
    lambda x: x+3,
    lambda x: x-10,
    lambda x: x+1000,
    lambda x: x//2
]

job = pipeline(lambda x: x>0, operations)
job(3)  # fails because the sequence goes 3 -> 6 -> (-4) -> ...
job(8)  # is 500 because 8 -> 11 -> 1 -> 1001 -> 500

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM