[EMAIL PROTECTED] wrote: > Hi all, I'm not skilled at programming, so sorry for my ignorance.
?! Seems you met many not-so-nice programmers. > (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 Do you mean when to save a class attribute to an instance or how to calculate and save something _inside_ an instance? No matter what, it depends largely on your design. If some value is a permanent "feature" of an instance, it makes sense to save it as a member. If the value must always be calculated on the fly, it makes sense to use a function that returns it. Also check the docs on Python's "property" feature. > (2) > when to use class methods and when to use functions ? Functions are best used if you just "do" something that isn't focused on a specific class or object type. Class methods are best used if there is something to "do" that always needs the class object. > 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. Yep. But there are also recipes to let functions store and reuse parameters, I think. > 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. But only a class object, which exists when you have defined a class. Class methods don't operate on instances. All you asked depends much on specific design. So if you provide some details, I'm sure at least one here will have a hint. Regards, Björn -- BOFH excuse #208: Your mail is being routed through Germany ... and they're censoring us. -- http://mail.python.org/mailman/listinfo/python-list