I am trying to define static variables in this example code:
class test_object:
resolution_default_opts = {'e':{'ylims':[0,2],'xlabel':'resolution'},'t':{'ylog':True,'xlabel':'resolution'}}
ee_default_opts = {'eee':{'xlabel':'parameter number'}}
default_opts = {'resolution':test_object.resolution_default_opts,'ee':test_object.ee_default_opts}
def __init__(self,name):
self.name = name
def foo(self,input):
return default_opts[input]
an_instance = test_object('a_name')
print(an_instance.foo('ee'))
However when running the above I get the following error :
default_opts = {'resolution':test_object.resolution_default_opts,'ee':test_object.ee_default_opts}
NameError: name 'test_object' is not defined
My understanding is that the variables resolution_default_opts and ee_default_opts are static class variables and that I should be able to call them via test_object. or self., but evidently it is wrong.
What is causing this error and how could I still get foo to work as intended (ie return ee_default_ops when we input 'ee') ?
If it is relevant, the python version is : Python 3.8.10
CodePudding user response:
Within the scope of the class definition, the class itself hasn't been defined yet (hence the NameError
), but the class variables are in the local scope, so you can refer to them directly.
Within the scope of the method definition, the class variables aren't in the local scope, but at the time the method is executed the class has been defined so you can use that to refer to them (you can also use self
).
class test_object:
resolution_default_opts = {'e':{'ylims':[0,2],'xlabel':'resolution'},'t':{'ylog':True,'xlabel':'resolution'}}
ee_default_opts = {'eee':{'xlabel':'parameter number'}}
default_opts = {'resolution':resolution_default_opts,'ee':ee_default_opts}
def __init__(self, name):
self.name = name
def foo(self, i):
return test_object.default_opts[i]
an_instance = test_object('a_name')
print(an_instance.foo('ee'))