I was doing some reading
here, and the author is discussing getter/setters in python. He compares the concept with Java.
Near the end he does this:
Code:
class Contact(object):
def __init__(self, first_name=None, last_name=None,
display_name=None, email=None):
self.first_name = first_name
self.last_name = last_name
self.display_name = display_name
self.email = email
def print_info(self):
print self.display_name, "<" + self.email + ">"
def set_email(self, value):
if '@' not in value:
raise Exception("This doesn't look like an email address.")
self._email = value
def get_email(self):
return self._email
email = property(get_email, set_email)
Implements getter/setters, with a exception in the setter property. So far I get it.
Then he proceeds to say, what
NOT to do, and demonstrates this:
Code:
class Contact(object):
def __init__(self, first_name=None, last_name=None,
display_name=None, email=None):
self.set_first_name(first_name)
self.set_last_name(last_name)
self.set_display_name(display_name)
self.set_email(email)
def set_first_name(self, value):
self._first_name = value
def get_first_name(self):
return self._first_name
def set_last_name(self, value):
self._last_name = value
def get_last_name(self):
return self._last_name
def set_display_name(self, value):
self._display_name = value
def get_display_name(self):
return self._display_name
def set_email(self, value):
self._email = value
def get_email(self):
return self._email
def print_info(self):
print self.display_name, "<" + self.email + ">"
However, besides the exception, isn't that what you did in your previous code above? I'm I missing something? The author implements the email getter/setter methods, and then proceeds to say in the code at the bottom, don't do it that way.
What should be done? How would a python programmer handle creating the contact class with getter/setter properties?