wrufesh wrufesh - 7 months ago 11
Python Question

Python class read only variable without '_' at beginning of the name

Hi I have a class representing or local calendar(other than AD)
Here I want all those class attributes to be read only

class BSDate(object):

def __init__(self, year, month, date):
self._year = year
self._month = month
self._date = date


In Python interpretor, I want to get month so I have to do like this:

x = BSDate(2072,5,2)
x._month


but I want to get month by simply calling

x.month


How can I solve this.

Answer

You can use @property to emulate a getter method

@property
def year(self):
    return self._year

@property
def month(self):
    return self._month

@property
def date(self):
    return self._date

Now when your client code can be:

my_date = BSDate(y, m, d)
month = my_date.month
year = my_date.year
date = my_date.date