Hi,

On 29 June 2011 18:53, Adam Moore <[email protected]> wrote:

> Ok, so I've been trying to understand how SmyPy performs basic
> simplification. I've traced through to when __add__(self, other) is
> called in expr.py and returns Add(self, other). What I don't
> understand is how does an Add object get created when __new__ and
> __init__ are not implemented in the Add class?
>
> For example, I see where Basic calls obj = object.__new__(cls), which
> in a case cls would be Add, but how is the Add object created that way
> if there is no implementation of __new__ or __init__ in Add?
>
> And also, I haven't found ANY __init__ reimplementations anywhere, but
> only __new__. Why is this?
>

Both __init__ and __new__ methods can be used to construct instances of
classes in Python, however __new__ is more flexible because allows us to
precisely control all aspects of instance creation. One of most important
features of Cls.__new__ is that it allows to construct an object that is
unrelated to Cls. This is useful for canonicalization of input arguments in
subclasses of Basic. For example

In [1]: Add(x, y, z)
Out[1]: x + y + z

In [2]: type(_)
Out[2]: <class 'sympy.core.add.Add'>

In [3]: Add(1, 2, 3)
Out[3]: 6

In [4]: type(_)
Out[4]: <class 'sympy.core.numbers.Integer'>

Add's __new__ method is defined in its base class, AssocOp. AssocOp calls
flatten() which is defined in Add (and also in Mul), and which performs
canonicalization of inputs, and then AssocOp.__new__, based on results from
flatten(), decides whether return an instance of Add/Mul or something else
(e.g. a Number as in the example above).


>
> Thanks,
>
> Adam
>
> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected].
> For more options, visit this group at
> http://groups.google.com/group/sympy?hl=en.
>
>
Mateusz

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

Reply via email to