Lucy
Lucy

Reputation: 125

Python class methods

In Python, which is the best way (style wise) to allow public access to an object's variables?

There are lots of options I've seen from different languages, I was wondering which of these (if any) is the preferred Python method? These are the options I'm currently torn between:

  1. Allow direct access to object variables (e.g. print(object.variable)), ignore data hiding
  2. Allow access to object variables by a wrapper function:

class X:
    variable_a = 0
    variable_b = 0
...
    def get_variable_a(self):
        return self.variable_a

If this is the recommended way, how do you name the methods? (get_variablename(), or just variablename etc?)

What does everyone recommend for this?

thanks!

Lucy

Upvotes: 3

Views: 830

Answers (4)

AndiDog
AndiDog

Reputation: 70128

You can use

Getters and setters (Java like)

class SomeClass(object):
  ...

  def get_x(self):
    return self._x
  def set_x(self, x):
    self._x = x

c = SomeClass()
print c.get_x()
c.set_x(10)

Properties (C# like)

class SomeClass(object):
  ...

  def get_x(self):
    return self._x
  def set_x(self, x):
    self._x = x
  x = property(get_x, set_x)

c = SomeClass()
print c.x
c.x = 10

I think it is merely a matter of style. Choose the one you like better. Same applies to the naming convention, choose one convention and stick to it.

In any case, data hiding can be done with pseudo-private variables (beginning with two underscores). They cannot be accessed directly, as opposed to the example variables (_x not starting with two underscores).

Upvotes: -1

Sunny Milenov
Sunny Milenov

Reputation: 22310

There are no "private" variables in Python. Check section 9.6 of this document http://docs.python.org/tutorial/classes.html

There is a convention though, that the users of the class should treat variables with names, starting with underscore to be not touched directly. Still, there is no mechanism which may prevent this.

Same with the mangled names (starting with 2 underscores).

Upvotes: 3

Ants Aasma
Ants Aasma

Reputation: 54882

Just allow direct access to any variables that you wish to expose as the public API. If you need to change the behavior you can always turn it into a property later on.

Notice that this is orthogonal to information hiding. obj.get_some_implementation_detail() is no better than obj.some_implementation_detail.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

Don't bother using accessors until they're necessary; converting a simple attribute to a property is quick and easy, and doesn't need modification of client code.

When I write a property, I use _get_FOO() and _set_FOO() for the accessors, and _FOO for the attribute itself.

Upvotes: 4

Related Questions