overloading for ladder logic

Benjamin Kaplan benjamin.kaplan at case.edu
Fri Nov 7 10:03:57 EST 2008


On Fri, Nov 7, 2008 at 8:48 AM, <jimzat at gmail.com> wrote:

> I am trying to simulate the execution of some PLC ladder logic in
> python.
>
> I manually modified the rungs and executed this within python as a
> proof of concept, but I'd like to be able to skip the  modification
> step.  My thought was that this might be able to be completed via
> overloading, but I am not sure if (or how) it could be done.
>
> overloadings:
>    + ==> OR
>    * ==> AND
>    / ==> NOT
>
> Example original code:
>     A=/B+C*D
> translates to:
>    A=not B or C and D
>
> I tried
>    def __add__ (a,b):
>        return (a or b)
>
> which gives me this:
>
>    >>> x=False
>    >>> y=True
>    >>> x+y
>        1
>    >>> x=True
>    >>> x+y
>        2
>
> How can this be done?
> --


Python doesn't have operator overloading like C does. What you can do is
define what the operators will do when used with a custom class. You will
see code like this:

class Foo(object):
   def __init__(self, value) :
      self.value = value
   def __add__(self, other) : #determines what happens when you have Foo +
something
      return (self or other)
   def __nonzero__(self) : #determines if the object evaluates to True
      return bool(self.value)

Now you can call

>>> bool(Foo(True) + Foo(False))
True
>>> bool(Foo(False) + Foo(False))
False

If you don't cast it to a bool, , you will get something that looks like
<__main__.Foo object at 0x86170>, but it will still work as an argument to a
conditional.

>
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081107/6cf9246e/attachment-0001.html>


More information about the Python-list mailing list