(sorry for just now replying. I am catching up on emails)

Usually when you subclass from Expr, you define __new__, since it's very
common for subclasses constructors to return a different class (e.g.,
Add(x, x) returns Mul(2, x), an instance of Mul).

The best way to see how to do this is to look for examples in the SymPy
code base, but the general idea is something like

class YourClass(Expr):
    def __new__(cls, *args, **kwargs): # replace *args with explicit
arguments if you have them
        # Do initialization stuff
        return super(YourClass, cls).__new__(*args, **kwargs) # alternately
return some other class

To use the original __mul__, you can use super. Or, structure your __mul__,
__rmul__ logic so that it happens automatically with the dispatch system.

As for whether or not do subclass from Expr, any thing that you want to
play nicely with the rest of SymPy should subclass at least from Basic. If
you want it to play nicely with things like Add and Mul, you should also
subclass from Expr (which is itself a subclass of Basic).  Subclassing from
Basic gives you lots of nice expression tree manipulation methods like subs
and atoms for free. Subclassing from Expr gives you basic mathematical
manipulation methods like expand for free.

Aaron Meurer


On Tue, Apr 30, 2013 at 3:35 PM, Alan Bromborsky <[email protected]>wrote:

> In the past when I wanted to add functionality to a python expression I
> would wrap it in a class as below -
>
> class ga(object):
>
>     def __init__(self,sympy_**expression):
>
>         self.obj = sympy_expression
>
>
>     more functions to add functionality, etc.
>
> Would it be better to derive my class from Expr as in -
>
> class ga(Expr):
>
>     def __init__(self,sympy_**expression):
>
>         what next?
>
> I can find no __init__ for Expr so how do I initialize it,  how do I refer
> to it
> in my class so I can manipulate it,  how do I use the original __mul__ if
> I override __mul__ ?
>
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to 
> sympy+unsubscribe@**googlegroups.com<sympy%[email protected]>
> .
> To post to this group, send email to [email protected].
> Visit this group at 
> http://groups.google.com/**group/sympy?hl=en-US<http://groups.google.com/group/sympy?hl=en-US>
> .
> For more options, visit 
> https://groups.google.com/**groups/opt_out<https://groups.google.com/groups/opt_out>
> .
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sympy?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to