Python class methods

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

There are many options that I saw in different languages, I was wondering which one (if any) is the preferred Python method? These are the options that I am currently tearing between:

  • Allow direct access to object variables (e.g. print (object.variable)), ignore data hiding
  • Allow access to object variables using the 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, what do you call methods? (get_variablename () or just variablename, etc.?)

What does everyone recommend for this?

thank!

Lucy

+3
source share
4 answers

, ; .

, _get_FOO() _set_FOO() _FOO .

+4

Python "private". 9.6 http://docs.python.org/tutorial/classes.html

, , , , . , , .

( 2 ).

+3

, API. , .

, . obj.get_some_implementation_detail() obj.some_implementation_detail.

+2

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)

(, #)

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

, . , . , .

In any case, data hiding can be done using pseudo-private variables (starting with two underscores). They cannot be accessed directly , unlike variable examples ( _xnot starting with two underscores).

-1
source

Source: https://habr.com/ru/post/1733687/


All Articles