开发者

Python: How should I make instance variables available?

开发者 https://www.devze.com 2023-01-02 07:04 出处:网络
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 insta

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? Sho开发者_Python百科uld I add a get_foo method to myclass or perhaps add a foo property? What's the best practice here?


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.


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.


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消