1

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

1 Answer 1

2

You can access previously defined class variables.

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

    def __init__(self, x):
        self.x = x
Sign up to request clarification or add additional context in comments.

3 Comments

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 Yeah I believe it's not possible for the reasons you describe. stackoverflow.com/questions/11058686/…. You can use staticmethods though, but the code to do so is a bit unwieldy stackoverflow.com/questions/41921255/…
yeah. I saw some of that. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.