Usage of the __and__ method

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Thu May 31 01:55:44 EDT 2007


On May 30, 10:11 pm, theju <thejaswi.puthr... at gmail.com> wrote:
> Hello all,
> I've two objects (both instances of a class called Person) and I want
> to use the __and__ method and print the combined attributes of the two
> instances.
>
> To be precise, here is my code....
>
> class Person:
>     def __init__(self,name):
>         self.name = name
>     def print_name(self):
>         print self.name
>     def __and__(self,other):
>         self.name = '%s AND %s' %(self.name,other.name)
>         return self.name
>
> p = Person("John")
> q = Person("George")
>
> r = p and q
> print r.print_name()


Try:

class Person(object):
    def __init__(self, name):
        self.name = name
    def __and__(self, other):
        return '%s AND %s' % (self.name, other.name)

p = Person("John")
q = Person("George")

r = p & q
print r


(1) A "getter" method (like your print_name
method) is usually not needed, just access the
attribute of the instance.  Like,

print p.name

(2) I doubt that you want the __and__ special
method to alter the name attribute of an
instance.

(3) You want to use the '&' operator
to dispatch to the __and__ method; __and__
is typically used for Numeric objects.

(4) You misunderstood how the 'and' operator
is used.  The expression 'p and q' causes p to
be evaluated; if p is false, its value is returned;
otherwise q is evaluated and its value is returned.

--
Hope this helps,
Steven




More information about the Python-list mailing list