[Tutor] How to shorten this code using classes?

Alan Gauld alan.gauld at btinternet.com
Fri Nov 25 01:37:09 CET 2011


On 23/11/11 17:09, James Reynolds wrote:

> However, as far as your question. For the two functions, you could
> subclass Button and add them to your new Button object:
>
> (untested)
>
>
> class MyButton(Button):
>      button_color="green"
>      button_value=False

But I'd move these into __init__() since otherwise all buttons will have 
the same color/value. Usually we want to change color/value of each 
button independently.
Also the button_ bit is redundant because they are now attributes of a 
Button, so we don;t need to repeat that in the name.

>      def __init__(self, *args, **kwargs):
>          super(Button, self).__init__(*args, **kwargs)
            self.color="green"
            self.value=False

So this becomes:
>      def change_value_and_color(self):
>          self.button_value = not self.button_value
            self.value = not self.value

>          if self.button_value:
            if self.value:
>              self.button_color="red"
                self.color="red"
>              self.configure(bg=self.button_color, text="Hi_2")
 >              self.configure(bg=self.color, text="Hi_2")

>          else:
>              self.button_color="green"
                self.color="green"
>              self.hello_bttn1.configure(bg=self.button_value, text="Hi_1")
 >              self.configure(bg=self.color, text="Hi_2")

But notice both self.configure lines are identical (assuming the second 
is not really supposed to be setting the background to value...)so we 
can pull them out of the if/else and add them after:

            self.configure(bg=self.button_color, text="Hi_2")


>      def button_clicked(self):
> """ This method runs if button one is clicked"""
>          self.change_value_and_color()


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list