#

Wednesday, August 27, 2025

Private Memberships & Property Decorator of OOP in Python for Network Engineers

Private Memberships

We can have Private Attributes and Private Methods inside a Class which should be accessed from within the Class only. It is just something Python community use, not something enforced. It is just an  These can be seen mostly inside Modules where the authors use the "_" at the beginning of the attribute / method indicating, don't try to call it from outside the Class which may break the functionality.

Here in this example, you can see that "_domains" is a private attribute. There can be private methods as well which starts with "_". 

However you can modify it if you want, when you call it from somewhere else with using "_" Infront of the attribute / method.
 
Property Decorator with Getters & Setters

A decorator in Python is a function that takes another function as its argument, and returns another function. Property Decorator in Python is a built in decorator 

In this example, we can see _name and _id are private attributes. 

As an example, 1st Syntax @property (line 6) and the method under it (line 7-8) is just coded to return the value of "_name" when just "name" is called from outside the class or anywhere in the program. If this method is not created, the value of _name can be outputted only by calling "R1._name". Because of this method, it is possible to call the same with "R1.name()". But to me more Pythonic, we can use Property Decorator (which is what we have done here with @property keyword), we can call just like a natural attribute "R1.name".



This @property is called a "Getter" as it is used to get values.





Setters can be used to set another value to an attribute, based on a condition.

Line 14 starts a "Setter" which sets a new value (line 22) later given in the program to the original value ( line 20) if the condition on line 16 matches else it will pop up the error message.

No comments:

Post a Comment