En Wed, 14 Mar 2007 18:04:00 -0300, Darren Dale <[EMAIL PROTECTED]> escribió:
> I've run across some code in a class method that I don't understand: > > def example(self, val=0) > if val and not self: > if self._exp < 0 and self._exp >= -6: 0) "Normal" methods are not class methods, but instance methods. A class method is a method who operates on the class itself; its first argument is the class (maybe a derived one). > I am unfamiliar with some concepts here: > > 1) Under what circumstances would "if not self" be True? "if not self" would be "if self evaluates to False as a boolean": 0, 0.0, 0j, (), [], {}... Other objects usually evaluate always to True, except if they define some special methods: __nonzero__ and __len__. Look those on the Python Reference Manual. > 2) If "not self" is True, how can self have attributes? Perhaps you think of self being None - that should never occur unless you called the method in some convoluted way. The class migh inherit from list, by example, and you want to compute the average: class StatList(list): def avg(self): if self: return sum(self)/len(self) else: raise ValueError("Can't compute average on empty list") > (This is slightly simplified code from the decimal.Decimal.__str__ > method, > line 826 in python-2.4.4) A Decimal number is False when 0. `if not self` is a faster way to say `if self==0` -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list