0

I'd like to initialize the class data all at once instead of after the class is declared. I realize the class variables / methods aren't accessible during the definition.

I've done the following to be able to initialize a variable based on class variable. I'm not thrilled with this, but I haven't seen something I like.

so:

  1. what are the downsides to doing what I've done?
  2. would it better to just initialize the rest of the class after the definition? that just looks wrong to me, but I'm new to python and still getting used to it.
class foo:

    stuff=[1,3,5,7]

    @property
    def data(self):
        print('...init...')
        value = sum(self.stuff)
        setattr(foo, 'data', value)
        return value

    def __init__(self, x):
        self.x = x

f=foo(1)
g=foo(2)

print(f.data)
print(f.data)
print(g.data)

print()

print(f.x)
print(g.x)

Output

...init...
16
16
16

1
2
martineau
  • 119,623
  • 25
  • 170
  • 301
kdubs
  • 1,596
  • 1
  • 21
  • 36

1 Answers1

1

You can access previously defined class variables.

class foo:
    stuff = [1, 3, 5, 7]
    data = sum(stuff)

    def __init__(self, x):
        self.x = x
rchome
  • 2,623
  • 8
  • 21
  • SOB. that's way too easy. never thought to try without a prefix on the variable. is there a way to call class methods? I'm guessing no, because there's no "handle" you can use for the class. – kdubs Dec 09 '21 at 12:35
  • 1
    @kdubs Yeah I believe it's not possible for the reasons you describe. https://stackoverflow.com/questions/11058686/various-errors-in-code-that-tries-to-call-classmethods. You can use staticmethods though, but the code to do so is a bit unwieldy https://stackoverflow.com/questions/41921255/staticmethod-object-is-not-callable – rchome Dec 09 '21 at 18:17
  • yeah. I saw some of that. thanks – kdubs Dec 10 '21 at 00:33