简体   繁体   中英

Setting attribute for class object in python that is slow to load

I am attempting to create a list of video objects, which have a name attribute which is set on initiation and then other attrs. that are loaded from ffprobe call fetching metadata. The ffmpeg calls are obviously slower to run, so I have written the class as follows:

class Video:

    def __init__(self, path, name):
        self.name = name
        self.path = path

    def get_length(self):
        if self.length:
            return self.length
        else:
            self.length = slow_function()
        return self.length

This way I can just fetch the attribute at a point of time where I need to reference the attr and the value is "set" on the "get" call.

Is this the proper way to do this? Is there a better way?

Thanks.

Slightly cleaner would be to initialize self.length to None , then call the slow function if self.length is still None .

class Video:

    def __init__(self, path, name):
        self.name = name
        self.path = path
        self.length = None

    def get_length(self):
        if self.length is None:
            self.length = slow_function()

        return self.length

Such lazily defined attributes are usually implemented with a property .

class Video:

    def __init__(self, path, name):
        self.name = name
        self.path = path
        self._length = None

    @property
    def length(self):
        if self._length is None:
            self._length = slow_function()

        return self._length

Now you can access length as what appears to be a regular (though read-only) attribute

v = Video(...)
print(v.length)

rather than an explicit method call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM