views:

81

answers:

5

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?

+5  A: 

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.

tzaman
It's also worth noting that unlike languages like C#, it can be changed from a field (dumb) to a property (arbitrary code) without changing the signature. So you don't need to prematurely make it a property.
Matthew Flaschen
@Matthew: exactly :) you commented just as I was updating my answer to include that.
tzaman
@tzaman Thanks for a very clear answer.
swisstony
@swisstony: you're quite welcome. :)
tzaman
+1  A: 

I think it should be alright to expose "foo" as it is. Even if you hide it behind a "getter", an insistent user will still be able to access it. As tzaman mentioned "we're all adults here".

If you wish to restrict the usage a bit (ie. make it harder to set), you might consider exposing it using a property. Properties are particularly handy if you need to expose an attribute that has been derived based on others.

bebraw
+1  A: 

Python tutorial has a very nice and concise discussion about this, so check it out. As there is no access control in Python, and recomendation is: if there is something you would make private in C++, start the name with an _ in Python and "play nice". Otherwise just access it directly.

djipko
+1  A: 

My suggestion, go for the easiest! Directly access the instance variables.

You can argue that if you change the inner representation of your data, you would like to access the data the same way without caring about the inner representation. But hey ! if you have get_foo and set_foo, semanticaly, it means you're changing a variable. So just do so :)

PS: I love the ruby approach there :)

Tristram Gräbener
+1  A: 

Depends on what you mean by "available to users of myclass". I think that you are talking about a class attribute, like this:

>>> class Myclass(object):
...     foo = "bar"
...
>>> a = Myclass()
>>> a.foo
'bar'
>>> b = Myclass()
>>> b.foo
'bar'
>>> Myclass.foo = "zot"
>>> a.foo
'zot'
>>> b.foo
'zot'
>>>
John Machin