Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing members or make them private in Python?

Is there a general convention about exposing members in Python classes? I know that this is a case of "it depends", but maybe there is a rule of thumb.

Private member:

class Node:

  def __init__(self):
    self.__children = []

  def add_children(self, *args):
    self.__children += args

node = Node()
node.add_children("one", "two")

Public member:

class Node2:

  def __init__(self):
    self.children = []

node2 = Node2()
node2.children += "one", "two"

If there is no good reason to make children private, would you stay with the method add_children?

like image 290
deamon Avatar asked Aug 11 '26 23:08

deamon


1 Answers

The prefix for "private" is a single underscore. __ is used to mangle the name and avoid some problems e.g. when using multiple inheritance. Personnally I've never used it.

In any case, the members will still be publicly accessible; this is just a convention.

like image 143
Bastien Léonard Avatar answered Aug 14 '26 12:08

Bastien Léonard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!