wrufesh wrufesh - 2 years ago 72
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)

but I want to get month by simply calling


How can I solve this.

Answer Source

You can use @property to emulate a getter method

def year(self):
    return self._year

def month(self):
    return self._month

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download