[Tutor] Class access rules

Alan Gauld alan.gauld at yahoo.co.uk
Mon Mar 7 06:42:04 EST 2022


On 07/03/2022 00:33, Phil wrote:

> class Led:
>      def __init__(self, pos, state=False, size=10):
> 
>      def toggle(self):
>          self.state = not self.state
> 
> I'm thinking of adding a blink method (I'm not sure what use it would 
> be). 

Don't add methods you don't need (search YAGNI). One of the insanely
great things about OOP is that it allows you to easily extend classes
to add methods if you need them later:

class BlinkingLed(Led):
   def blink(self, rate=1):
      # ideally put this loop in a thread
      if not rate: #stop any existing blinks
      while rate:
         self.toggle()
         sleep(rate)

> have specific methods (draw circle and blink) for wxpython and tkinter? 

The professional answer to this is that you should create the
Led as a data object (a "Model") that does the logic of switching
state/blinking or whatever and have a separate "View" object
that does the drawing on the GUI.

Then you can have Tkinter and wxPython view objects and the same
generic model object. You need to connect the model and view
obviously but that can be as simple as passing the model to
the view when you create it.

This is a large part of the famous Model View Controller
architecture used in most modern GUIs and web frameworks.

The amateur approach is just do it for the GUI you are
actually using and worry about multi-platform as and
when you need it!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list