Python Data Persistence – Getters/setters
Java class employs getter and setter methods to regulate access to private data members in it. Let us see if it works for a Python class. Following code modifies myclass.py and provides getter and setter methods for my name and my age instance attributes.
Example
#myclass.py class MyClass: __slots__=['myname', 'myage'] def__init__(self, name=None, age=None): self.myname=name self,myage=age def getname(self): return self.myname def set name(self, name): self.myname=name def getage(self): return self.myage def setage(self, age): self.myage=age def about(self): print ('My name is { } and I am { } years old' ,format(self.myname,self.myage) )
The getters and setters allow instance attributes to be retrieved / modified.
Example
>>> from myclass import MyClass >>> obj1=MyClass('Ashok',21) >>> obj1.getage( ) 21 >>> obj1.setname('Amar') >>> obj1.about( ) My name is Amar and I am 21 years old
- Python Data Persistence – class Keyword
- Python Data Persistence – property () Function
- Python Data Persistence – @Property DGCOrator
Good enough. However, this still doesn’t prevent direct access to instance attributes. Why?
Example
>>> obj1.myname 'Amar' >>> getattr(obj1,'myage') 21 >>> obj1.myage=25 >>> setattr(obj1myname1, 'Ashok') >>> obj1.about() My name is Ashok and I am 25 years old
Python doesn’t believe in restricting member access hence it doesn’t have access to controlling keywords such as public, private, or protected. In fact, as you can see, class members (attributes as well as methods) are public, being freely accessible from outside the class. Guido Van Rossum – who developed Python in the early 1990s – once said, “We ‘re all consenting adults here” justifying the absence of such access restrictions. Then what is a ‘Pythonic’ way to use getters and setters? The built-in property () function holds the answer.