OOP & Abstract Classes

Peter Otten __peter__ at web.de
Mon May 11 20:59:41 CEST 2009


Adam Gaskins wrote:

> So I was beginning to learn OOP for PHP, and it seemed to me that abstract
> classes were just right for my application. In my application I must
> communicate with several peices of test equipment that communicate via
> RS-232. Most use SCPI instructions, some do not and require low level
> communication.
> 
> The way I understand abstract classes is that I could have a class that
> has all my abstract methods such as 'init', 'getMeasurement',
> 'setPressure', etc... then I could use this common interface to to control
> my different pieces of hardware (after I write a library for each of
> them).
> 
> Is this a valid application for abstract classes? Or am I making life more
> complicated than it need be?
> 
> Now, I have read that Pythons OOP implimentation is so much better and
> more complete then PHP's, but I cant find anything about abstract classes
> except this:
> http://norvig.com/python-iaq.html
> 
> ...which says it doesn't exist in Python and you can only do this hack to
> make it work (and I don't particularly understand how to impliment it from
> this article).

It is basically a non-implementaton. If you don't understand it you should 
not mess with abstract base classes and work your way through an 
introductory python textbook. 

That said, the page is outdated; Python 2.6 has some support for abstract 
classes. They even fail a bit earlier, when the class is instantiated 
instead of when the method is called. Example:

from abc import ABCMeta, abstractmethod, abstractproperty

class AbstractDevice:
    __metaclass__ = ABCMeta

    @abstractmethod
    def init(self):
        pass

    @abstractproperty
    def pressure(self):
        pass


class Compressor(AbstractDevice):
    def init(self):
        print "starting compressor"

    def set_pressure(self, value):
        print "setting pressure to", value
    pressure = property(fset=set_pressure)

c = Compressor()
c.init()
c.pressure = 42

a = AbstractDevice() # fails with TypeError

 
> This makes me suspect I am making things more comlicated than they need to
> be. Could someone help me understand the proper way to impliment a set
> classes/methods to deal with several peices of similar and not so similar
> hardware? Not looking for anyone to write code for me, just help
> understanding some of these OOP concepts and how they would apply to my
> situation.

Personally I would just write the class I need

class Compressor(object):
    def init(self):
        print "starting compressor"

    def set_pressure(self, value):
        print "setting pressure to", value
    pressure = property(fset=set_pressure)

and forget about the bureaucracy. Instead I recommend that you learn about 
unit tests and write a few tests to ensure your classes work as specified.

Peter




More information about the Python-list mailing list