Suppose I have a class like this:
class Hola(object):
NOMBRE = 'hola'
def muestro_cosas(self):
print('Mi nombre es {}'.format(Hola.NOMBRE))
class HolaPequenito(Hola):
NOMBRE = 'hola_pequenito'
...
As you can see, it HolaPequenito
is a subclass of Hola
.
Now, I do an implementation of things where I need to use the class variable NOMBRE
.
- If I have an instance of
Hola
, I will doprint (Hola.NOMBRE)
. - If I have an instance of
HolaPequenito
, I will doprint (HolaPequenito.NOMBRE)
.
However, there are times when I don't know if I will be instantiating Hola
or HolaPequenito
, because I instantiate them dynamically within a large process, in which I need to know the value of NOMBRE
the class that has been instantiated and do something like:
class Hola(object):
NOMBRE = 'hola'
def comprueba_cosas(self):
if NOMBRE == 'hola': # aquí debo usar la variable de clase
...
elif NOMBRE == 'hola_pequenito':
...
That is to say: if I instantiate Hola
or HolaPequenito
without knowing which of the two I am instantiating, how can I access the NOMBRE
respective class variable to do some heuristics?
The best I got was to define a class method that returns it to me :
class Hola(object):
NOMBRE = 'hola'
@classmethod
def bah(cls):
return cls.NOMBRE
But I don't know how to combine it to interact with the class variable NOMBRE
inside a method.