Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to pull default values from a file?

Tags:

python

Not a specific coding question so much as program structure in general.

I'm one of those poorly self taught hobby programmers and I've got no idea what the best route is here. I want to create an object with 4 variables (name, objID, a, and b). For example:

class myObj:
    def __init__(self, objName, objID):
        self.name = objName
        self.objID = objID
        self.a = 0
        self.b = 0

My question/problem is I want the initial values for a and b to be pulled from a .txt file, based on the value of objID. I actually want more than just 2 variables, and I'll be creating hundreds of these objects with a dozen different types.

I don't think I want to read the file from this class, as I believe it will reopen the file every time an object is created, and I don't really like pulling it into a list/array/dictionary and passing it to the class because the myObj class will only be called from an object above it, also with dozens of instances.

To clarify - I plan to create 100 'topObj' objects, each with 5-10 'myObj' objects, with each 'myObj' having starting values (that will change later), pulled from a text file, and I don't know when and where to read the data from the text file without reading it 500-1000 times.

Hopefully this makes some semblance of sense.

Thanks,
db_

like image 960
db_ Avatar asked Dec 01 '25 02:12

db_


1 Answers

I don't think I want to read the file from this class,

Probably not since the class represents one entry and so you'd have to search the entire file for it on each entry, as you said.

and I don't really like pulling it into a list/array/dictionary and passing it to the class because the myObj class will only be called from an object above it, also with dozens of instances.

You don't have to store it in the instance, if you don't like that.

Just read the entire file into a dictionary and pass it where you need it. It's not like it's cloning the dictionary each time.

topObj then can give all the myObj constructors that dictionary. It's always the same dictionary anyhow, I don't get what's supposedly bad about it, quite the opposite: it's explicit and so it's the Python way.

You probably need some way of quickly finding entries and that's how you can do that.

pulled from a text file

From just one text file, independent of the topObjs? Then read the contents of the text file into a dictionary and pass that (you can put that into a load function to have it tidy if you want that).

like image 101
Danny Milosavljevic Avatar answered Dec 03 '25 18:12

Danny Milosavljevic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!