When to use classes?
Ken Seehof
kens at sightreader.com
Sun Mar 5 16:01:53 EST 2000
I always use tuples for points. In C++, I could never make up my mind on
this issue since one of the reasons for having a class is simply to gather x
and
y into one object for convenience.
In python, tuples give you an alternative. Typically my functions/methods
start out like this:
def f(p):
x,y = p
I'd probably write a polygon as a class wrapping a list of tuples. This is
a very common approach for me: express the data atomically, then wrap
it in a class.
class polygon:
def __init__(self, pt_list = []):
self.pt_list = pt_list[:]
...
Advantages of point as tuple:
Easier to integrate with other software
Most readable coordinate packing/extraction: x,y = p p = x,y
Advantages of point as class:
Handy vector operators: p1 = p3 - p2 p = p*2
Scott Bahling wrote:
> I am just starting to use python and I love it so far.
>
> I have a couple of philosophical questions about OOP programming with
> python.
>
> First: When and when not to create a new class? An example would be if I
> have a class for a Polygon, I need to store a set of points defining the
> polygon object. One method would be to store a list of tuples containing
> the polygon's points. If I want to access the individual x and y coords
> of each point, I end up with code that looks like:
>
> firstxcoord = poly.points[0][0]
> firstycoord = poly.points[0][1]
>
> Or I could create a Point class and use a list of them in the Polygon
> class. Then I would have code that looks like:
>
> firstxcoord = poly.points[0].x
> firstycoord = poly.points[0].y
>
> The second piece of code is easier to read. But lets say that this Point
> class has no other purpose but to contain two numerical values; is the
> use of a Point class overkill? Is there a 'rule of thumb' for when to
> create a new class?
>
> Second: What is the general consensus about accessing instance variables
> directly like myobj.x=10 vs. through methods like myobj.setx(10). The
> first method is quicker/easier to code, but is it "bad" coding? Does
> anyone even care?
>
> I know these are general OOP questions. I am asking in case there are
> aspects of the python language that would help to determine when and
> when not to do these things.
>
> -thanks
>
> scott
More information about the Python-list
mailing list