On 2007-05-20, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi all, I'm not skilled at programming, so sorry for my ignorance. > My questions: > > (1) > which is the better way to calculate the value of attributes of a class ? > for example: > > (A) > def cal_attr(self, args): > #do some calculations > self.attr = calculated_value > and then if the vlue of attribute is needed, > self.cal_attr(args) > some_var = self.attr > or I can define cal_attr() as follows: > (B) > def cal_attr(self, args): > #do some calculations > return calculated_value > and then, if the value of attribute is needed, > self.attr = self.cal_attr(args) > some_var = self.attr
It looks from your example like this attr depends on the args passed to cal_attr. Is it really then an "attribute" of the object, or just the result of a calculation that the object provides? If the latter, you might not want the variable self.attr at all, and just write some_var = self.cal_attr(args) Otherwise self.attr just ends up storing the result of the previous call to cal_attr. Is that useful? Does any other part of the program actually need that? If not don't store it. > (2) > when to use class methods and when to use functions ? I think you just mean methods (Python has something special called "class methods" which are for, er, well, you almost never need them). > In my opinion, both of class methods and functions have advantages and > disadvantages. I have to pass many arguments to a function, which is > annoying. When using class methods, the arguments can be stored as > attributes of the class, which is convenient for later use. But I have > to create an object in advance. That's about right. There's no hard and fast rule. If you need those values again it may be worth storing them, but be wary of storing computed values if there's a chance they're going to get out of date. > I have googled the web, but haven't found too much specific answers. > Can somebody kindly answer my questions or point me to the resources > available on the web ? You're asking good questions and they don't have easy answers. -- http://mail.python.org/mailman/listinfo/python-list