I have a class with a complex data member that I want to keep “static”. I want to initialize it once, using a function. How Pythonic is something like this:
def generate_data():
... do some analysis and return complex object e.g. list ...
class Coo:
data_member = generate_data()
... rest of class code ...
The function generate_data takes a long while to complete and returns data that remains constant in the scope of a running program. I don’t want it to run every time class Coo is instantiated.
Also, to verify, as long as I don’t assign anything to data_member in __init__, it will remain “static”? What if a method in Coo appends some value to data_member (assuming it’s a list) – will this addition be available to the rest of the instances?
Thanks
You’re right on all counts.
data_memberwill be created once, and will be available to all instances ofcoo. If any instance modifies it, that modification will be visible to all other instances.Here’s an example that demonstrates all this, with its output shown at the end: