Question

Whilest learning Python 3 and converting some of my code from Java to Python 3.3 I came across a small problem I haven't been able to fix.
In Java I have this code (just dummy code to make it smaller):

public enum Mapping {
    C11{public int getMapping(){ return 1;}},
    C12{public int getMapping(){ return 2;}},
    public abstract int getMapping();
}

String s = "C11";
System.out.println(Mapping.valueOf(s))

Works fine and prints the requisted '1' Trying to do this in Python doesn't work that easy (yet). I tried to imitate an Enum with:

class Mapping:
    C11=1
    C12=2

s = 'C11'
print(Mapping.Mapping.(magic should happen here).s)

Unfortunately I have no idea how to convert a string to an attribute to be called like that (or something similar). I need this because I have a HUGE list in the class Mapping and need to convert seemingly random words read from a text file to an integer mapping.

Was it helpful?

Solution

You are looking for getattr:

>>> getattr(Mapping, s)
1

From the documentation:

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

OTHER TIPS

Use getattr:

class Mapping:
    C11=1
    C12=2

print(getattr(Mapping, 'C11')) # prints 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top