__str__, __add__, __mul__,__nonzero__,__norm_cval,__cmp__ : method « Class « Python Tutorial






class NumStr(object):
    def __init__(self, num=0, string=''):
        self.__num = num
        self.__string = string

    def __str__(self):        
        return '[%d :: %r]' % (self.__num, self.__string)
    __repr__ = __str__

    def __add__(self, other):     # define for s+o
        if isinstance(other, NumStr):
            return self.__class__(self.__num + other.__num, self.__string + other.__string)
        else:
            raise TypeError, 'Illegal argument type for built-in operation'

    def __mul__(self, num):       # define for o*n
        if isinstance(num, int):
            return self.__class__(self.__num * num, self.__string * num)
        else:
           raise TypeError, 'Illegal argument type for built-in operation'

    def __nonzero__(self):        # False if both are
        return self.__num  or len(self.__string)

    def __norm_cval(self, cmpres):# normalize cmp()
        return cmp(cmpres, 0)

    def __cmp__(self, other):     # define for cmp()
        return self.__norm_cval(cmp(self.__num, other.__num)) + self.__norm_cval(cmp(self.__string, other.__string))

          

a = NumStr(3, 'foo')
b = NumStr(3, 'goo')
c = NumStr(2, 'foo')
d = NumStr()
e = NumStr(string='boo')
f = NumStr(1)
print a
print b
print c
print d
print e
print f
print a < b
print b < c
print a == a
print b * 2
print a * 3
print b + e
print e + b
if d: 'not false'     # also bool(d)
if e: 'not false'     # also bool(e)
print cmp(a,b)
print cmp(a,c)
print cmp(a,a)








11.4.method
11.4.1.Methods in class
11.4.2.Intermediate Customization
11.4.3.Any Number of Items Iterator
11.4.4.__str__, __add__, __mul__,__nonzero__,__norm_cval,__cmp__
11.4.5.Wrapping Standard Types
11.4.6.The property() built-in function can take up to four arguments.
11.4.7.A setter
11.4.8.stick in a documentation string for your attribute
11.4.9.Here is our modified class inspired by the recipe:
11.4.10.Class Time with accessor methods.
11.4.11.Methods calling
11.4.12.Add method to a class from outside