Is there a way to access class attributes during param declaration?

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?

Thanks in advance for any help!

Hi @ckingdon95 !

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:

  1. 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 :upside_down_face:
  2. 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
2 Likes

If what you want is just setting the value of example.p and not anything more, it is as simple as:

import param

class Example(param.Parameterized):
    p = param.Number()
    
example = Example(p=1)

image

3 Likes

amazing, thank you both! what I’m actually trying to do is more complicated than this, so both your answers are very helpful info :slight_smile:

2 Likes