Hello, I am new to using param, and I am trying to figure out if there is a way to access class attributes during the creation of a param. Is there a way to do something like the following:
import param
class example(param.Parameterized):
def __init__(self, default_p):
self.default_p = default_p
p = param.Number(default = self.default_p)
x = example(5)
This errors with: name 'self' is not defined. I guess this comes down to me not understanding the scope during the declaration. Is there a way for me to access self.default_p during this step?
Yes indeed you can’t get access to self in a Parameter declaration, as self is not in their scope. You can achieve what you want by:
don’t forget to call super().__init__, the class you create inherits from param.Parameterized and if you don’t do that you basically override the super class __init__, which won’t have any good consequence
each Parameter can be accessed with self.param.paramname or self.param[paramname] (similarly to how you get reference columns in a Pandas DataFrame). From there you can set the default value.
import param
class P(param.Parameterized):
s = param.String()
def __init__(self, s_default, **params):
super().__init__(**params)
self.param.s.default = s_default
p = P('default')
Note that in the example I shared:
the default is just set for this instance, not at the class level, so if you create another instance you have to set the default again
setting the default doesn’t automatically change the value of the Parameter, if that’s what you want you will also have to do that in the __init__ with self.s = s_default