正确说明状态槽功能

时间:2018-11-16 16:36:03

标签: python python-3.x function

我有一个具有不同功能的代码。在其中一个内部有一个条件。我必须检查是否发生这种情况才能执行另一个功能。

执行此操作的正确方法是什么?我已经尝试过类似的方法,但是它不起作用

示例:

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)的榜样,我根本没有考虑过。不过,也许不是那么优雅。

更新2 另一种方法是通过这种方式使用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()

1 个答案:

答案 0 :(得分:1)

我必须先进行模式转换,然后才能对值进行一系列转换,并且每次都需要通过测试。您可以使用以下方法构造它:

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