0

I'm fairly new to oop and had a quick question about constructors. From an API call i get a large response of which I only want to preserve a subset in a class based data structure. This is the approach i was thinking about, but I think i would be calling the api twice, whereas, I just want to call it once , preserve the data and then extract pieces into the constructors.

I could call the api, outside of the function, just passing in the appropriate values into the constructors, but thought it might be cleaner to keep all the logic in the folder class.

Example code

class folder():
    def __init__(self, id):
       self.id = id
       self.name = get_folder_metadata(id).name
       self.region = get_folder_metadata(id).region

    def get_folder_metadata(id):
        f_metadata = '''api call''' getfolder(id) ''' done '''
        return f_metadata

Curious if either is best practice or there are other ways i'm not thinking about. Thanks for any help.

hselbie
  • 1,749
  • 9
  • 24
  • 40
  • Since you call `__init__` a constructor, here's some relevant reading: [`__init__` as a constructor?](https://stackoverflow.com/questions/6578487/init-as-a-constructor) – Abdul Aziz Barkat Nov 04 '22 at 17:01

1 Answers1

0

I'm solving like this for the moment, but curious if others have thoughts.

class folder():
    def __init__(self, id):
       self.id = id
       self.folder_metadata = self.get_folder_metadata(id)
       self.name = self.folder_metadata.name
       self.region = self.folder_metadata.region

    def get_folder_metadata(id):
        f_metadata = '''api call''' getfolder(id) ''' done '''
        return f_metadata
hselbie
  • 1,749
  • 9
  • 24
  • 40
  • You do know that `__init__` is also a method so you can have a locally scoped variable? You don't really need to add everything as an attribute there you can totally write `folder_metadata = self.get_folder_metadata(id)` and that would be fine there... – Abdul Aziz Barkat Nov 04 '22 at 16:59