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
class Car: numberOfWheels = 4 _colour = "Black" #protected attribute __yearOfManufacture = '2017' ## private
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
car = Car() print("Public attribute {}".format(car.numberOfWheels))
Public attribute 4
bmw = BMW()
Protected attribute colour of car is :Black and the car has 4
Lets access the private variable outside of the class
print("Accessing the private variable: ", car.__yearOfManufacture)
--------------------------------------------------------------------------- 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
print("Accessing the private variable YearOfManufacture: ", car._Car__yearOfManufacture)
('Accessing the private variable YearOfManufacture: ', '2017')
The full code can be found below:
Credit to Four Pillars of Object Oriented Programming on Udemy