繁体   English   中英

Python字典中的访问函数

[英]Accessing function in Python dictionary

class Solution:
    def add(x) -> int:
        return x + 1

    def sub(x) -> int:
        return x - 1

    def finalValueAfterOperations(self, operations: List[str]) -> int:
        switch = {"X++": add, "++X": add, "X--": sub, "--X": sub}
        x = 0
        for i in range(len(operations)):
            x = switch[operations[i]](x)

        return x

执行此操作时出现错误:

TypeError: unsupported operand type(s) for -: 'Solution' and 'int'
    x = switch[operations[i]](self,x)
Line 20 in finalValueAfterOperations (Solution.py)
    ret = Solution().finalValueAfterOperations(param_1)

我用"X++": lambda x : x+1替换了所有情况下的函数,它可以工作。 我如何使它适用于功能?

您不可能从粘贴的代码中得到粘贴的错误。

无论如何,假设您确实希望将事物封装在一个类中(无论出于何种原因),问题是您需要将操作定义为自由函数,例如

from typing import List


def add(x) -> int:
    return x + 1


def sub(x) -> int:
    return x - 1


class Solution:

    def compute(self, operations: List[str], x=0) -> int:
        switch = {"X++": add, "++X": add, "X--": sub, "--X": sub}
        for op in operations:
            x = switch[op](x)

        return x


print(Solution().compute(["X++", "++X", "X--"]))

或作为真正的方法并这样称呼它们:

from typing import List


class Solution:

    def add(self, x) -> int:
        return x + 1

    def sub(self, x) -> int:
        return x - 1

    def compute(self, operations: List[str], x=0) -> int:
        switch = {"X++": self.add, "++X": self.add, "X--": self.sub, "--X": self.sub}
        for op in operations:
            x = switch[op](x)

        return x


print(Solution().compute(["X++", "++X", "X--"]))

或者可能是@staticmethod ,因为您不需要self

from typing import List


class Solution:

    @staticmethod
    def add(x) -> int:
        return x + 1

    @staticmethod
    def sub(x) -> int:
        return x - 1

    def compute(self, operations: List[str], x=0) -> int:
        switch = {"X++": self.add, "++X": self.add, "X--": self.sub, "--X": self.sub}
        for op in operations:
            x = switch[op](x)

        return x


print(Solution().compute(["X++", "++X", "X--"]))

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM