Declare Public Protected and Private Variables in Python – Object Oriented Programming
In Python, the scope ( Public, Protected, Private) characteristic of an attribute or member of the class is indicated by “the naming conventions of the member”. These are the naming conventions
Public: This means the member can be accessed outside of the class by other instances. The naming convention denotes that it has no underscores eg numberOfFields = 6 Protected: This means that the member can be accessed by the Parent Class and its “Children” – those classes that inherit the parent class The naming convention denotes that it has ONE underscore in front of the member name eg _numberOfFields = 6 Private This means the member is only accessible within the parent class. The naming convention denotes that it has TWO underscores in front of the member name eg __numberOfFields = 6
Lets check some examples
Let’s create a Car class and a BMW class the inherits from the Car Class
1 2 3 4 |
class Car: numberOfWheels = 4 _colour = "Black" #protected attribute __yearOfManufacture = '2017' ## private |
1 2 3 |
class BMW(Car): def __init__(self): print("Protected attribute colour of car is :{} and the car has {}".format(self._colour, self.numberOfWheels)) |
Lets instantiate both classes and see how the attributes behave
1 2 |
car = Car() print("Public attribute {}".format(car.numberOfWheels)) |
1 |
Public attribute 4 |
1 |
bmw = BMW() |
1 |
Protected attribute colour of car is :Black and the car has 4 |
Lets access the private variable outside of the class
1 |
print("Accessing the private variable: ", car.__yearOfManufacture) |
1 2 3 4 5 6 |
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-21-f33c89bb066a> in <module>() ----> 1 print("Accessing the private variable: ", car.__yearOfManufacture) AttributeError: Car instance has no attribute '__yearOfManufacture' |
Though we are strongly advised not to use the private variable outside of the class we can actually access it like below
1 |
print("Accessing the private variable YearOfManufacture: ", car._Car__yearOfManufacture) |
1 |
('Accessing the private variable YearOfManufacture: ', '2017') |
The full code can be found below:
Credit to Four Pillars of Object Oriented Programming on Udemy