Ronan Lamy wrote:
> Le vendredi 20 novembre 2009 � 16:15 -0500, Alan Bromborsky a �crit :
>
>> I am looking at the Basic class and wonder what you are doing with the
>> following statement:
>>
>> def __new__(cls, *args, **assumptions):
>> obj = object.__new__(cls)
>>
>> What I am trying today is give the Symbol class a new data member so
>> that is x is a symbol I can define
>> x.latex_name to go with
x.name. However the __new__ command for symbol
>> is inscrutable to me so that if I define
>> a cls.latex_name in __new__ for symbol it is global to the class. I
>> asked about the above statement since the
>> __new_stage2__ function returns a basic object and there is where the
>> symbol name is stored.
>>
>
> object.__new__ is the default object creator. The statement you cite
> creates an empty instance (= without any instance attribute) of the
> class cls and assigns it to the empty variable obj.
> Generally speaking, __new__ is a special method that is called to create
> instances of a class. Its return value is the instance you want to
> create. A statement like x = Symbol(name, ...) is basically syntactic
> sugar for x = Symbol.__new__(Symbol, name, ...). If Symbol, which is a
> subclass of Basic, did not override Basic.__new__, the statement would
> be equivalent to x = Basic.__new__(Symbol, name, ...) � compare the 2nd
> line of __new_stage2__.
>
> Note that __new__ is always a class method, which means that its first
> argument is the class you want to instantiate (that's the reason why
> it's called "cls"). So, writing cls.latex_name = <whatever> will
> obviously create a *class* attribute. What you want is to create an
> *instance* attribute. For that, you simply need to take your
> newly-created instance (i.e. "obj", after the second line of
> __new_stage2__) and add an attribute to it in the usual, straightforward
> manner (i.e. obj.latex_name = <whatever>)
>
> Hope this helps.
> Ronan
>
> --
>
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To post to this group, send email to
sy...@googlegroups.com.
> To unsubscribe from this group, send email to
sympy+un...@googlegroups.com.
> For more options, visit this group at
http://groups.google.com/group/sympy?hl=.
>
>
>
If I modify __new_stage2__ to:
def __new_stage2__(cls, name, commutative=True, **assumptions):
assert isinstance(name, str),`type(name)`
obj = Basic.__new__(cls, **assumptions)
obj.is_commutative = commutative
print '__new_stage2__(name) =',name
obj.latex_name = None
if '|' in name:
namelst = name.split('|',1)
name = namelst[0]
obj.latex_name = namelst[1]
obj.name = name
return obj
I get the error:
File "/home/brombo/sympy/sympy/core/symbol.py", line 61, in __new_stage2__
obj.latex_name = None
AttributeError: 'Symbol' object has no attribute 'latex_name'
Any further suggestions would be welcome.