More specifically, I want to be able to support lambda: , but I want to keep the code clear and to a concise. I have to validate the value, so I need a setter of some kind. I need to use lambda because I need to pass callbacks to Tkinter events. I also need to be able to modify the value of the attribute outside a binding.
In my following examples, assume that a button widget called spam_button has been declared globally. Also asume that the class Eggs will have at least 10 attributes than need to all be accessed the same way (I like consistency).
The first possible way I could do this is using just getters and setters:
class Eggs(object):
def __init__(self):
self._spam = ''
self.set_spam('Monster')
print self.get_spam()
spam_button.bind('', lambda: self.set_spam('Ouch'))
def set_spam(self, spam):
if len(spam) <= 32:
self._spam = spam
def get_spam(self):
return self._spam
But if I use this method and have lots of attributes, the code may get too long to manage.
The second way I could do this is use properties, and use the setter in the callback:
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam = 'Monster'
print self.spam
spam_button.bind('<Enter>', lambda: self.set_spam('Ouch'))
def set_spam(self, spam):
if len(spam) <= 32:
self._spam = spam
def get_spam(self):
return self._spam
spam = property(get_spam, set_spam)
This way is a bit simpler than the first when accessing the attribute directly, but is inconsistent when using lambda.
The third way to do this would be to make an additional class with get and set methods:
class Spam(object):
def __init__(self):
self._value = ''
def set(self, value):
if len(spam) <= 32:
self._value = value
def get(self):
return self._value
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam = Spam()
self.spam.set('Monster')
print self.spam.get()
spam_button.bind('<Enter>', lambda: self.spam.set('Ouch'))
This method is more organised than the first, but I will need to make a class for each type of validation.
The last way I might do it is use methods instead of properties (properties were the second example):
class Eggs(object):
def __init__(self):
self._spam = ''
self.spam('Monster')
print self.spam()
spam_button.bind('', lambda: self.spam('Ouch'))
def spam(self, spam=None):
if spam != None:
if len(spam) <= 32:
self._spam = spam
else:
return self._spam
This method will probably be the shortest, but it is harder at a glance to tell whether I am getting or setting.
Which (if any) of these methods are preferred?
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)