Python: Accessing class variables from other class

2019-09-09 19:43发布

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条回答
在下西门庆
2楼-- · 2019-09-09 20:08

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.

查看更多
登录 后发表回答