Home > other >  Is it bad to put expensive statements in static class attributes if class is instantiated often?
Is it bad to put expensive statements in static class attributes if class is instantiated often?

Time:06-23

I have a class with the following structure.

class MyClass:
    
    my_variable = pickle.load(open("my_file.p", "rb"))

    def __init__(self):
        .
        .
        .

I assume, pickle.load() is an expensive operation that is why I am wondering if it will get called every time I instantiate the class, or is it just once when the file is imported?

CodePudding user response:

All class attributes (my_variable, __init__, etc) are defined when the class is defined. Methods like __init__ are called when the class is instantiated, but none of the class attributes are redefined at that point.

pickle.load will only be called once, when MyClass is first defined.


Basically, you can think of the class statement as being a declarative way of writing

def my_class_init(self):
    ...

namespace = {
    '__init__': my_class_init,
    'my_variable': pickle.load(...)
}

MyClass = type('MyClass', (), namespace)

with pickle.load only being called to define the dict bound to namespace.

CodePudding user response:

it will load one time when the class instance is created and this class attribute (my_variable) is shared among all the class instances, and any modification is shared among all. so it is one time operation.

  • Related