Class attributes newbie question (before I join a cargocult)

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Mar 12 19:02:17 EST 2006


On Sun, 12 Mar 2006 10:53:57 -0800, pclinch wrote:

> See __slots__ and PyChecker for possible ways to avoid misspelled
> instance variables.

__slots__ are not meant as a way to implement variable declarations.
__slots__ are meant as a memory optimization for cases where you have
large numbers (tens of thousands?) of almost identical instance variables
and you don't need to dynamically add or delete attributes.

Of course, just because __slots__ were invented for one purpose doesn't
mean that you can't find another use for them, but this is not the way.
PyChecker is a good solution for testing for misspelled variables. Another
way is to avoid setters and getters: instead of creating a method to
change the name and sex of the instance, just change the attributes
directly. Not getters and setters means less code, and less code means
fewer bugs (whether due to misspellings or not).


The Original Poster, EP, wrote:

>>     def changeName(self, newname=""):
>>         self.name=newname
>>         return self.name

This is not a very Pythonic idiom. (I'm not saying that it is *wrong*,
merely that it is unusual.) Generally, methods should implement one of two
behaviours, as illustrated by the following simplified example:

class Number(object):
    def __init__(self, num):
        self.value = num

    def __add__(self, other):
        """add two instances of Number and return a new instance"""
        return Number(self.value + other.value)

    def increment(self, inc):
        """increment this instance in place"""
        self.value += inc

>>> foo = Number(5)
>>> bar = Number(3)
>>> foo.increment(2)
>>> foo.value
7
>>> baz = foo + bar
>>> baz.value
10

In other words, methods should generally return either a new instance, or
nothing. Unless you have a good reason for it to act differently.



-- 
Steven.




More information about the Python-list mailing list