0

I have a class which has a lot of constants defined. I need to concatenate them by function call to make the code look cleaner. Below example should clarify this

I want to achieve this

class A:
    @staticmethod
    def __create_key(*keys):
        return '.'.join(keys)

    __CONST_A = 'const_a'
    __CONST_B = 'const_b'
    __CONST_C = 'const_c'
    __CONST_D = __create_key(__CONST_A, __CONST_B, __CONST_C)

When I run this code I run into the following exception

TypeError: 'staticmethod' object is not callable

Rather than doing the following

class A:
    @staticmethod
    def __create_key(*keys):
        return '.'.join(keys)

    __CONST_A = 'const_a'
    __CONST_B = 'const_b'
    __CONST_C = 'const_c'
    __CONST_D = __CONST_A + '.' + __CONST_B + '.' + __CONST_C

Or is there more elegant way to do this.

My main use case is that I have a bunch of these constant variables and I want to generate more constants by concatenating them

Stidgeon
  • 2,673
  • 8
  • 20
  • 28
iec2011007
  • 1,828
  • 3
  • 24
  • 38
  • Does this answer your question? [Calling class staticmethod within the class body?](https://stackoverflow.com/questions/12718187/calling-class-staticmethod-within-the-class-body) – Ryan Schaefer Apr 16 '20 at 05:59
  • 1
    A staticmethod is still a method a needs to be called on the class or an instance. Why not make it a standalone function and define it above the class. Then again, `','.join` is even shorter and more explicit then the function signature. – user2390182 Apr 16 '20 at 06:00
  • to call staticmethod you need to call it from the class, that mean the right way to write it is ```__CONST_D = A.__create_key(__CONST_A, __CONST_B, __CONST_C)``` instead of what you write. – assaf.b Apr 16 '20 at 06:10
  • @assaf.b when I do this it shows error ` NameError: name 'A' is not defined` – iec2011007 Apr 16 '20 at 06:19
  • Do you need the "method" only to create the class, or afterwards as well? – MisterMiyagi Apr 16 '20 at 06:20
  • @schwobaseggl agreed to ``` '.'.join ``` but this is just a dummy implementation, what if the logic is more involed, Additionally when i take the function out of the class or take it to the modules __init__.py then it says import error – iec2011007 Apr 16 '20 at 06:21
  • @assaf.b Concerning the Name Error, please take a look at the second linked question. It deals with exactly this approach. – MisterMiyagi Apr 16 '20 at 06:22

0 Answers0