0

I'm a bit tired of typing MyLongAdvancedClassName._template to access class variables. They are sometimes constants, but not always. You will say I want to use module globals in case of constants. But I want to have them defined near to the place of usage, not in the beginning of file. I also don't like locals, because in case of a long string you will reallocate it on each call.

Is it possible to do something like the following:

_c = MyLongAdvancedClassName

class MyLongAdvancedClassName:
    ...

    _template = " My long advanced text %i "
    def method(self):
        print _c._template
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
noname7619
  • 3,370
  • 3
  • 21
  • 26
  • 2
    You can do that, but you have to move the `_c = ...` line after the class definition. – BrenBarn May 11 '16 at 05:45
  • 1
    I always just used `self._template`, with the understanding that the instance variable is not quite tied to the class variable. These class variables are constants for me, so I have not yet encountered any issues because I have never needed to reassign either. I don't know if this is a frowned-upon practice, though. – Waleed Khan May 11 '16 at 05:54

2 Answers2

3

You can make use of self keyword in python instead of using the current class name.

class MyLongAdvancedClassName:
    ...

    _template = " My long advanced text %i "
    def method(self):
        print self._template

Hope it helps.

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
Strik3r
  • 1,052
  • 8
  • 15
2

Probably what you are looking for is to use self (look at San's answer). However this requires you to have an instance of the class. If you want to do it with the class itself then you can use the classmethod decorator like this:

class MyLongAdvancedClassName:
    ...

    _template = " My long advanced text %i "
    @classmethod
    def method(cls):
        print cls._template
Matthias Schreiber
  • 2,347
  • 1
  • 13
  • 20