Python классы приватные поля

Python — Public, Protected, Private Members

Classical object-oriented languages, such as C++ and Java, control the access to class resources by public, private, and protected keywords. Private members of the class are denied access from the environment outside the class. They can be handled only from within the class.

Public Members

Public members (generally methods declared in a class) are accessible from outside the class. The object of the same class is required to invoke a public method. This arrangement of private instance variables and public methods ensures the principle of data encapsulation.

All members in a Python class are public by default. Any member can be accessed from outside the class environment.

class Student: schoolName = 'XYZ School' # class attribute def __init__(self, name, age): self.name=name # instance attribute self.age=age # instance attribute 

You can access the Student class’s attributes and also modify their values, as shown below.

std = Student("Steve", 25) print(std.schoolName) #'XYZ School' print(std.name) #'Steve' std.age = 20 print(std.age) 

Protected Members

Protected members of a class are accessible from within the class and are also available to its sub-classes. No other environment is permitted access to it. This enables specific resources of the parent class to be inherited by the child class.

Python’s convention to make an instance variable protected is to add a prefix _ (single underscore) to it. This effectively prevents it from being accessed unless it is from within a sub-class.

class Student: _schoolName = 'XYZ School' # protected class attribute def __init__(self, name, age): self._name=name # protected instance attribute self._age=age # protected instance attribute 

In fact, this doesn’t prevent instance variables from accessing or modifying the instance. You can still perform the following operations:

std = Student("Swati", 25) print(std._name) #'Swati' std._name = 'Dipa' print(std._name) #'Dipa' 

However, you can define a property using property decorator and make it protected, as shown below.

class Student: def __init__(self,name): self._name = name @property def name(self): return self._name @name.setter def name(self,newname): self._name = newname 

Above, @property decorator is used to make the name() method as property and @name.setter decorator to another overloads of the name() method as property setter method. Now, _name is protected.

std = Student("Swati") print(std.name) #'Swati' std.name = 'Dipa' print(std.name) #'Dipa' print(std._name) #'Dipa' 

Above, we used std.name property to modify _name attribute. However, it is still accessible in Python. Hence, the responsible programmer would refrain from accessing and modifying instance variables prefixed with _ from outside its class.

Читайте также:  Html css open close

Private Members

Python doesn’t have any mechanism that effectively restricts access to any instance variable or method. Python prescribes a convention of prefixing the name of the variable/method with a single or double underscore to emulate the behavior of protected and private access specifiers.

The double underscore __ prefixed to a variable makes it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:

class Student: __schoolName = 'XYZ School' # private class attribute def __init__(self, name, age): self.__name=name # private instance attribute self.__salary=age # private instance attribute def __display(self): # private method print('This is private method.') std = Student("Bill", 25) print(std.__schoolName) #AttributeError print(std.__name) #AttributeError print(std.__display()) #AttributeError 

Python performs name mangling of private variables. Every member with a double underscore will be changed to _object._class__variable . So, it can still be accessed from outside the class, but the practice should be refrained.

std = Student("Bill", 25) print(std._Student__name) #'Bill' std._Student__name = 'Steve' print(std._Student__name) #'Steve' std._Student__display() #'This is private method.' 

Thus, Python provides conceptual implementation of public, protected, and private access modifiers, but not like other languages like C#, Java, C++.

  • Class Attributes vs Instance Attributes in Python
  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles
Читайте также:  While несколько раз php

Источник

№33 Приватные переменные / для начинающих

Приватные переменные — это те переменные, которые видны и доступны только в пределах класса, которому они принадлежат. В Java приватные переменные объявляются с помощью ключевого слова private , которое дает к ним доступ только переменным и методам внутри этого же класса. Такие методы не могут быть перезаписаны извне. В Python такого нет — вместо этого используются два символа нижнего подчеркивания ( __ ) для любых переменной или метода, которые должны считаться приватными.

Как работают приватные переменные в Python?

На практике в Python нет приватных методов и переменных, как в Java. Здесь задействованы два символа нижнего подчеркивания в начале любой переменной или метода, которые нужно сделать приватными. Когда переменные объявляются приватными, подразумевается, что их нельзя будет изменять, как в случае с публичными. Последние доступны из любого класса, поэтому их значения могут меняться, что часто приводит к различным конфликтам. Рассмотрим на примере, как в Python используются приватные переменные.

Примеры реализации приватных переменных

 
class Mainclass:
__private_variable = 2020;

def __private_method(self):
print("Это приватный метод")

def insideclass(self):
print("Приватная переменная:", Mainclass.__private_variable)
self.__private_method()

foo = Mainclass()
foo.insideclass()

Приватная переменная: 2020
Это приватный метод

В программе выше есть класс Mainclass , внутри которого имеются приватные переменные методы, объявленные с помощью двух подчеркиваний: __private_variable и __private_method . Получить к ним доступ можно только в пределах этого класса. Если же попробовать сделать это из другого класса, то вернется ошибка, сообщающая, что в классе нет такого атрибута. Это же можно продемонстрировать и на другом примере.

 
class Mainclass:
__private_variable = 2020

def __private_method(self):
print("Это приватный метод")

def insideclass(self):
print("Приватная переменная:", Mainclass.__private_variable) foo = Mainclass()
foo.insideclass()
foo.__private_method()

Private Variable: 2020
Traceback (most recent call last):
File «C:\Python37\da.py», line 13, in
foo.__private_method()
AttributeError: ‘Mainclass’ object has no attribute ‘__private_method’

В этой программе можно обратить внимание на то, что метод приватный, но доступ к нему пытаются получить вне класса Mainclass , поэтому возвращается ошибка, которая сообщает, что у класса нет экземпляра этого атрибута. Таким образом по умолчанию все методы и переменные внутри класса являются публичными, но методы с двумя подчеркиваниями в названии становятся приватными, и получить к ним доступ можно только внутри того же класса.

Процесс превращения переменных или методов в локальные называется «искажением данных» или «искажением имен» (data/name mangling). Он используется для избежания неоднозначности при определении имен подклассов. Это же помогает перезаписывать методы подклассов без прерывания вызовов методов внутри класса.

Настоящая приватность в Python не поддерживается, а ту, что есть, называют «слабым индикатором внутреннего использования». Для нее есть один символ нижнего подчеркивания ( _ ), который используется для объявления приватных переменных, методов, функций и классов в модуле.

 
class Vehicle:
def _start_engine(self):
return "Создаем мотоцикл."

def run(self):
return self._start_engine() if __name__ == '__main__':
bike = Vehicle()
print(bike._start_engine())
print("Мотоцикл создан.")
bike.run()
print("Мотоцикл запущен.")

Создаем мотоцикл.
Мотоцикл создан.
Мотоцикл запущен.

В последнем примере нижнее подчеркивание используется для метода _start_engine чтобы сделать его приватным. Но такое подчеркивание применяется не часто, потому что оно лишь подразумевает, что к этому объекту нельзя будет получить доступ извне, а двойное подчеркивание означает то же, но соблюдается строже.

Одиночное подчеркивание используется не очень часто, потому что если метод с одним подчеркиванием изменяют любую переменную класса и при этом вызывается, то возможны конфликты в работе класса. Двойное подчеркивание же ( __ ) широко используется для объявления приватных переменных и избежания неоднозначности при определении имен подклассов. В Python не таких приватных переменных, как в C++ или Java.

Выводы

В большей части языков программирования есть 3 модификатора доступа: публичный, приватный и защищенный. В Python они тоже есть, но работают и поддерживаются не совсем так.

Приватные переменные — это те переменные, к которым можно получить доступ внутри класса, где они были объявлены. В Python для этого есть одиночные и двойные подчеркивания, хотя вторые используются куда чаще. С их помощью можно получать доступ изнутри класса и выполнять «искажение имен».

Источник

Оцените статью