I have a Language
class as such:
class _Language:
def __init__(self, name, bRightToLeft=False):
self.name = name
self.bRightToLeft = bRightToLeft
def isRightToLeft(self):
return self.bRightToLeft
def getName(self):
return self.name
class Language:
EN = _Language("English")
AF = _Language("Afrikaans")
SQ = _Language("Albanian")
And I create a Language object as such:
l1 = Language.EN
After some processing with the english
object, I would like to retrieve its "subtype", i.e. EN
. For instance:
print l1
[out]:
EN
I have tried adding __repr__
or a __str__
in the Language class but I'm not getting EN
when i print l1
:
class Language:
EN = _Language("English")
AF = _Language("Afrikaans")
SQ = _Language("Albanian")
def __str__(self):
return self.__name__
[out]:
Language
How could I access the variable name such that when I print l1
I get EN
?
Any individual
_Language
instance has no idea what two-letter name you have given it in theLanguage
namespace (or anywhere else, for that matter). So you have two possibilities:(1) Have each instance store that information, on pain of having to repeat yourself:
Of course, you can reduce the repetition by providing a class method on
Language
to create and register_Language
instances, rather than creating them at class definition time:This is probably the solution I'd favor personally.
(2) Have your
_Language.__str__
method search theLanguage
namespace to find out what name it's known by there:In this case, you could store the result so it only needs to be looked up once: