简体   繁体   English

python中枚举中的抽象方法

[英]abstract method in an enum in python

My question is, how to write this in python?我的问题是,如何用python写这个? Is something like this possible?这样的事情可能吗?

How it should work: I'm getting data from an algorithm that will decide which letter to output.它应该如何工作:我从一个算法中获取数据,该算法将决定输出哪个字母。 If there are certain conditions in the data that should not apply to one character, the conditions should be checked for another character.如果数据中的某些条件不适用于一个字符,则应针对另一个字符检查这些条件。 The data and the conditions are of course more complex than shown here.数据和条件当然比这里显示的要复杂。

Why enums: Because only this small main method has to be written in the algorithm file (iterable).为什么要枚举:因为只有这个小的 main 方法必须写在算法文件中(可迭代)。 And the conditions of the letters are encapsulated in another file and clearly structured.并且信件的条件被封装在另一个文件中并且结构清晰。

enum Letter {
    
    A () {
        public boolean condition(int[] args) {
            if (args[0] > args[1]) return false;
            if (args[1] > args[2]) return false;
            return true;
        }
    },
    
    B () {
        public boolean condition(int[] args) {
            if (args[0] > args[1]) return false;
            if (args[1] < args[2]) return false;
            return true;
        }
    },
    
    C () {
        public boolean condition(int[] args) {
            if (args[0] < args[1]) return false;
            if (args[1] < args[2]) return false;
            return true;
        }
    };
    
    public abstract boolean condition(int[] args);
    
}
public class Alphabet {
    
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        //int[] arr = {1, 2, 1};
        //int[] arr = {3, 2, 1};
        
        for (Letter l : Letter.values()) {
            if (l.condition(arr)) {
                System.out.println(l);
                break;
            }
        }
    }
}

While you could shoehorn an Enum into serving this purpose, it'd be much easier to just use a dict or list of functions that you can iterate over, eg:虽然您可以硬塞一个 Enum 来实现此目的,但使用可以迭代的 dict 或函数列表会容易得多,例如:

letters = [
    ("A", lambda args: args[0] <= args[1] <= args[2]),
    ("B", lambda args: args[0] <= args[1] >= args[2]),
    ("C", lambda args: args[0] >= args[1] >= args[2]),
]

def alphabet(args):
    print(next(letter for letter, condition in letters if condition(args)))

alphabet([1, 2, 3])  # A
alphabet([1, 2, 1])  # B
alphabet([3, 2, 1])  # C

Or with type annotations (these are optional in Python, but they allow you to do static type analysis/testing similar to what you get in a compiled language, and can make tricky code easier to understand):或者使用类型注释(这些在 Python 中是可选的,但它们允许您进行类似于在编译语言中获得的静态类型分析/测试,并且可以使棘手的代码更容易理解):

from typing import Callable, List, Tuple

Condition = Callable[[List[int]], bool]

letters: List[Tuple[str, Condition]] = [
    ("A", lambda args: args[0] <= args[1] <= args[2]),
    ("B", lambda args: args[0] <= args[1] >= args[2]),
    ("C", lambda args: args[0] >= args[1] >= args[2]),
]

def alphabet(args: List[int]) -> None:
    print(next(letter for letter, condition in letters if condition(args)))

Note that in the type-annotated version, we can just define Condition as a handy type alias for "a function that takes a list of ints and returns a bool".请注意,在类型注释版本中,我们可以将Condition定义为“一个接受整数列表并返回布尔值的函数”的方便类型别名。 We don't need to actually make a new class or define a new abstract interface, since functions are first-class objects in Python and their interface already fits this use case perfectly.我们不需要实际创建一个新类或定义一个新的抽象接口,因为函数是 Python 中的一等对象,它们的接口已经完美地适合这个用例。

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

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