{"id":8278,"date":"2023-11-09T18:43:35","date_gmt":"2023-11-09T13:13:35","guid":{"rendered":"https:\/\/python-programs.com\/?p=8278"},"modified":"2023-11-10T12:24:04","modified_gmt":"2023-11-10T06:54:04","slug":"python-data-persistence-getters-setters","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-data-persistence-getters-setters\/","title":{"rendered":"Python Data Persistence – Getters\/setters"},"content":{"rendered":"
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.<\/p>\n
Example<\/strong><\/p>\n The getters and setters allow instance attributes to be retrieved \/ modified.<\/p>\n Example<\/strong><\/p>\n Good enough. However, this still doesn\u2019t prevent direct access to instance attributes. Why?<\/p>\n Example<\/strong><\/p>\n Python doesn\u2019t believe in restricting member access hence it doesn\u2019t 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, \u201cWe ‘re all consenting adults here\u201d justifying the absence of such access restrictions. Then what is a \u2018Pythonic\u2019 way to use getters and setters? The built-in property () function holds the answer.<\/p>\n","protected":false},"excerpt":{"rendered":" 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’] …<\/p>\n#myclass.py\r\nclass MyClass:\r\n__slots__=['myname', 'myage']\r\ndef__init__(self, name=None, age=None):\r\nself.myname=name\r\nself,myage=age\r\ndef getname(self):\r\nreturn self.myname\r\ndef set name(self, name):\r\nself.myname=name\r\ndef getage(self):\r\nreturn self.myage\r\ndef setage(self, age):\r\nself.myage=age\r\ndef about(self):\r\nprint ('My name is { } and I am { } years old' ,format(self.myname,self.myage) )<\/pre>\n
>>> from myclass import MyClass\r\n>>> obj1=MyClass('Ashok',21)\r\n>>> obj1.getage( )\r\n21\r\n>>> obj1.setname('Amar')\r\n>>> obj1.about( )\r\nMy name is Amar and I am 21 years old<\/pre>\n
>>> obj1.myname\r\n'Amar'\r\n>>> getattr(obj1,'myage')\r\n21\r\n>>> obj1.myage=25\r\n>>> setattr(obj1myname1, 'Ashok')\r\n>>> obj1.about()\r\nMy name is Ashok and I am 25 years old<\/pre>\n