Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How should I make instance variables available?

Suppose I have:

class myclass:
  def __init__(self):
    self.foo = "bar"

where the value of foo needs to be available to users of myclass. Is it OK to just read the value of foo directly from an instance of myclass? Should I add a get_foo method to myclass or perhaps add a foo property? What's the best practice here?

like image 252
FunLovinCoder Avatar asked Dec 17 '22 00:12

FunLovinCoder


1 Answers

The applicable Python maxim would be "we're all adults here" - if users need direct access to the value of foo, let them access it directly. A getter or property would make sense if you need to run some code when it's accessed, otherwise the direct way is best.

Also, you can always transparently turn it into a property later if you need to.

like image 89
tzaman Avatar answered Jan 15 '23 04:01

tzaman