Python: Accessing class variables from other class variables within the class - possible?

旧城冷巷雨未停 提交于 2019-12-14 03:14:57

问题


is it possible in python to address class variables from other class variables within the same class?

My problem is: I am trying to prepare some static code, that would look like this:

class MyBaseObject:
  SIGNAL_NAME_1 = "signal-name-1"
  SIGNAL_NAME_2 = "signal-name-2"

  ALL_SIGNALS = {
    SIGNAL_NAME_1: ( signal-definition ),
    SIGNAL_NAME_2: ( signal-definition ) }

My problem with the above is that, according to python SIGNAL_NAME_1 and _2 are not defined while creating dict. Accessing them by MyBaseObject.SIGNAL_NAME_1 also does not work (unknown object).

So question is - is it possible to have class variables referring to one another in python?

Thank you!


回答1:


No, there shouldn't be any problem referring to other class variables just using there names. You cannot however refer to MyBaseObject as that isn't defined until the class definition completes.

The code you posted will work just fine (if signal and definition are defined), so if you are getting complaints about names not being defined that means you didn't post the exact code you used. Try posting the exact code and the exact and complete error message.



来源:https://stackoverflow.com/questions/10267620/python-accessing-class-variables-from-other-class-variables-within-the-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!