Static class property pointing to special instance of the same class in Python -


coming cpp/c#, how 1 refer same class in class body in python:

class foo(object):     answer = foo(42)     fail = foo(-1)      def __init__(self, value):         self._v = value 

when try use code, "name 'foo' not defined" exception in line trying instantiate answer instance.

the name foo not set until full class body has been executed. way can want add attributes class after class statement has completed:

class foo(object):         def __init__(self, value):         self._v = value  foo.answer = foo(42) foo.fail = foo(-1) 

it sounds re-inventing python's enum module; lets define class constants instances of class:

 enum import enum   class foo(enum):      answer = 42      fail = -1 

after class statement has run, foo.answer instance of foo .value attribute set 42.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -