How to set a private property in Python? Is there protected property?

4

I come from PHP. In it, when we want to define a property of a class as private we add the keyword private in its declaration.

Example:

class StackOverflow extends StackExchange
{
    private $language = 'en'; // privado, só pode ser acessado via Accessor!

    public function __construct($language === null){

         if ($language !== null) {
             $this->language = $language;
         }

    }

   public function getLanguage()
   {
       return $this->language;
   }
}

Now I'd like to know how to do this in Python . How to set private property in this example below.

class StackExchange(object):
    def __init__(self):
        pass

class StackOverflow(StackExchange):

    language = 'en' // quero que seja privado ou protegido!

    def __init__(self, language = None):
        if language is not None:
            self.language = language


sopt = StackOverflow('pt')
sopt.language // retorna o valor, mas quero utilizar um Accessor ao invés disso

Another thing: In PHP, we use protected to define that the property can not be accessed in class instantiation, but can be accessed by itself and by who inherits it.

Can you do this in Python too?

    
asked by anonymous 04.03.2015 / 20:56

2 answers

2

According to @ JoãoPedroAlves, there is no private property .

For protected properties, this would be a schema using the @property and @nomedaproperty.setter modifiers . :

class StackExchange(object):
    def __init__(self):
        pass

class StackOverflow(StackExchange):
    # Coloque sua variável dentro de __init__, o que "evita" que ela vire pública.
    # Ela ainda é acessível através de _StackOverflow__language.
    def __init__(self, language = None):
        self.__language = 'en'
        if language is not None:
            self.__language = language

    @property # Objeto.language cai aqui
    def language(self):
        return self.__language

    @language.setter # Objeto.language = 'pt' cai aqui
    def name(self, language):
        self.__language = language

Here you can test .

    
04.03.2015 / 21:07
4

In Python there is this concept of private property.

Following the PEP 8 - Style Guide for Python Code , you can use% __ in front of a method as a convention. Recalling that his method will not be "private", but it would be a kind of convention for those who see your code know that this method (or variable) should only be used in the parent class.

Here's an excerpt from PEP 0008:

  

If your class is intended to be subclassed, and you have attributes   you do not want subclasses to use, consider naming them with   double leading underscores and no trailing underscores. This invokes   Python's name mangling algorithm, where the name of the class is   mangled into the attribute name. This helps avoid attribute name   collisions should subclasses inadvertently contain attributes with the   same name.

    
04.03.2015 / 21:13