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 ...
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
__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?
why defined '__new__' and '__init__' all in a class
How Can I Add a Class to the Body Tag using jQuery?
How to create a class from function
data_memberwill be created once, and will be available to all instances of
How can I make my objects/classes more portable?
If any instance modifies it, that modification will be visible to all other instances..
How to get public properties of a class?
Here's an example that demonstrates all this, with its output shown at the end:.
Adding a custom UI component as a panel titleIcon (should be easy, I'm kind of a newbie)
def generate_data(): print "Generating" return [1,2,3] class coo: data_member = generate_data() def modify(self): self.data_member.append(4) def display(self): print self.data_member x = coo() y = coo() y.modify() x.display() # Output: # Generating # [1, 2, 3, 4]
c# create an instance of an object from string
Using link_to in a class in a Rails helper
coo.data_memberitself, for example.
then the modification is seen by the rest of the instances.
However if you do .
then a new instance member is created which overrides the class member and is only visible to that instance, not the others.
self.data_member = new_object
The difference is not always easy to spot, for example
self.data_member += 'foo'vs.
self.data_member = self.data_member + 'foo'.. To avoid this you probably should always refer to the object as
data_member = generate_data()will be executed only once, when
class coo: ...is executed.
In majority of cases class statements occur at module level and are executed when module is imported.
data_member = generate_data()will be executed only once when you import module with class
coofor the first time.. All instances of
cooclass will share
data_memberand can access it by writing
Any changes made to
coo.data_memberwill be immediately visible by any
An instance can have its own
This attribute can be set by typing
self.data_member = ...and will be visible only to that instance.
data_membercan still be accessed by typing