I already define my class, and starts Ok, I have changed the operation to __mul__. But now I'd like to define an __add__ operation which surpass my knowledge...
Something like this, sage: A = MyClass( 3, "Hello") sage: B = MyClass( 4, "World!") sage: A+B ( 3, "Hello") + ( 4, "World!") sage: C = MyClass( 5, "World!") sage: B+C ( 9, "World!") I'm thinking could be a bit hard, since the function I'm defining has not a string but a matrix as second entry. The first is not a number either. Thx. Dox. On Feb 10, 3:42 am, Jason Grout <jason-s...@creativetrax.com> wrote: > On 2/9/11 9:18 PM, Robert Bradshaw wrote: > > > On Wed, Feb 9, 2011 at 6:43 PM, Dox<o.castillo.felis...@gmail.com> wrote: > >> Hi people! > > >> I was wondering if there is a way of bundle two kind of different > >> objects together and define operations on them. > > >> Suppose, I'd like to bundle a number and a string (3, Hello) and (4, > >> World!!)... then define and operation which multiplies the numbers and > >> add strings, so the result is (12, HelloWorld!!) > > >> Something like that! > > > Yes. See, for example, how the sage.misc.preparser.BackslashOperator > > is implemented. (I think we have a more generic one, but I'm not sure > > where it is.) > > I presume you mean the infix decorator from this patch: > > http://trac.sagemath.org/sage_trac/ticket/6245 > > I was going to point out the page in the reference manual, but > apparently somehow that file is not documented in the reference manual. > > Anyways, do infix_operator?, see sage.misc.decorator, or just look at > this example: > > sage: @infix_operator('add') > ....: def my_add(a,b): > ....: return (a[0]*b[0], a[1]+b[1]) > ....: > sage: (3,"Hello") +my_add+ (4, "World!!") > (12, 'HelloWorld!!') > > But it might make a lot more sense to make a simple class that prints > out the string and number and has an operation defined on it. > > sage: class MyClass: > ....: def __init__(self, num, s): > ....: self._num=num > ....: self._s=s > ....: def __add__(self, other): > ....: if isinstance(other, MyClass): > ....: return MyClass(self._num*other._num, self._s+other._s) > ....: raise NotImplemented > ....: def __repr__(self): > ....: return str((self._num, self._s)) > ....: def __str__(self): > ....: return self.__repr__() > ....: > sage: a=MyClass(3,"Hello") > sage: b=MyClass(4,"World!!") > sage: a > (3, 'Hello') > sage: b > (4, 'World!!') > sage: a+b > (12, 'HelloWorld!!') > > Thanks, > > Jason -- To post to this group, send an email to sage-devel@googlegroups.com To unsubscribe from this group, send an email to sage-devel+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/sage-devel URL: http://www.sagemath.org