Search code examples
pythonoopprivateaccess-specifier

How can you provide this access specifier protection in python?


Here is the scenario I am currently dealing with.
There is a class called Service. Basically, only a single object of this can be created by a node. Once this object is created it is passed from one node to another node.

Class Service:
 int valueOfA=0;
 int valueOfB=0;
 int valueOfC=0;
 int valueOfD=0;

Now , Lets say A instantiates an object obj of this class. now A should be able to increment only

 obj.valueOfA++

Similarly B should be able to increment only

 obj.valueOfB++

But any node can read the value of A or B or C. Here each node is identified by its IP address. Meaning node A has a separate IP addr, node B has a separate IP address so on and so forth.

How can I implement something like this in python?


Solution

  • Python has no automatic access specifier protection like public or private. But you can always implement the logic yourself using a method. Do something like:

    def incrementA(self, node):
      if node.name == "Node A": self.valueOfA += 1
      else: raise ValueError("node is not authorized to increment A")
    

    Also, Python has no ++ operator. You need to use += to increment.