|

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

 

Lets instantiate both classes and see how the attributes behave

 

Lets access the private variable outside of the class

 

Though we are strongly advised not to use the private variable outside of the class we can actually access it like below

 

 

The full code can be found below:

Credit to Four Pillars of Object Oriented Programming on Udemy

Want more information like this?

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *