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 Answers 5

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: exactly :) you commented just as I was updating my answer to include that.
1

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.

Comments

1

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.

Comments

1

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 :)

Comments

1

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'
>>>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.