what is the python version of saying this.. this is in java
public static enum Operations {Add, Subtract, Multiply, Divide, None};
I am converting an entire program to python, i just cant figure out this part
heres my whole class
import java.util.*;
public class Expression
{
public static enum Operations {Add, Subtract, Multiply, Divide, None};
int a;
int b;
Expression.Operations op;
public Expression()
{
a = 0;
b = 0;
op = Expression.Operations.None;
}
public Expression(int value1, int value2, Expression.Operations operation)
{
a = value1;
b = value2;
op = operation;
}
public boolean parseString(String expressionString, Map<Character, Integer> vars)
{
Scanner scanner = new Scanner(expressionString);
//Attempt to read the first value.
if (scanner.hasNextInt())
a = scanner.nextInt();
else if (scanner.hasNext())
{
String var = scanner.next();
//Ensure that the variable identifier is a single alphabetical character in length.
if (!var.matches("[A-Z]{1}"))
{
return false;
}
if (vars.containsKey(var.charAt(0)))
a = vars.get(var.charAt(0));
else
{
System.err.println("ERROR: Uninitialized variable.");
return false;
}
}
else return false;
//If more tokens exist, attempt to read the operator.
if (scanner.hasNext())
{
String operator = scanner.next();
if (operator.equals("+"))
op = Expression.Operations.Add;
else if (operator.equals("-"))
op = Expression.Operations.Subtract;
else if (operator.equals("*"))
op = Expression.Operations.Multiply;
else if (operator.equals("/"))
op = Expression.Operations.Divide;
else
return false;
//Attempt to read the second value.
if (scanner.hasNextInt())
b = scanner.nextInt();
else if (scanner.hasNext())
{
String var = scanner.next();
//Ensure that the variable identifier is a single alphabetical character in length.
if (!var.matches("[A-Z]{1}"))
{
return false;
}
b = vars.get(var.charAt(0));
}
else return false;
}
return true;
}
public int evaluate()
{
int value = 0;
if (op == Expression.Operations.Add)
value = a + b;
if (op == Expression.Operations.Subtract)
value = a - b;
if (op == Expression.Operations.Multiply)
value = a * b;
if (op == Expression.Operations.Divide)
value = a / b;
if (op == Expression.Operations.None)
value = a;
return value;
}
}
In Python any attribute or method is considered public unless you put underscores at the start of its name. Here is the relevant section in the Python 2.7 tutorial.
Python doesn’t have a way of exactly duplicating the function of
static, but any attributes you define on a class will be visible in instances in the same way asstaticvariables are. Justattribute = valueinside your class definition and you’re fine.You can’t make values
constantin Python, but the convention is to useUPPERCASE_IDENTIFIERSto indicate that intention.Enums do not exist. In Python ordinary strings constants are usually used for this purpose. Just pass
"add""subtract","multiply","divide"orNoneto your function.For example, in your parser
would become
and in your evaluator
would become