structs in python

Sean 'Shaleh' Perry shalehperry at attbi.com
Sun Jul 7 00:26:00 EDT 2002


On 07-Jul-2002 Kevin O'Connor wrote:
> Hello,
> 
> I often find myself using Python tuples in the same way I might use C
> structs.  For example, I might store a "point" as "p = (x, y, color)".
> 
> Unfortunately, this quickly becomes cumbersome when the code starts to make
> frequent references to tuple positions instead of member names.  For
> example, one would see code like "delta = (p1[0] - p2[0], p1[1] - p2[1])".
> Ideally, this code would read something more like "delta = (p1.x - p2.x,
> p1.y - p2.y)".
> 
> Clearly, the use of classes makes the code much more readable, but
> unfortunately the declarations necessary to instantiate a class is often
> too much of a hassle for small and infrequently used objects.
> 
> It would be useful if there were a simple way of declaring a class with
> only member variables (and no methods); an object more akin to a C struct.
> 

>>> class Point:
...   pass
... 
>>> p = Point()
>>> p.x = 1
>>> p.y = 2
>>> p.color = "blue"
>>> p2 = Point() 
>>> p2.x = 3
>>> p2.y = 5
>>> p2.color = "green"

However this breaks down for your delta = ... example.

is

class Point:
  def __init__(x, y, color):
    self.x = x
    self.y = y
    self.color = color

really that much to type?

delta = Point(p2.x - p.x, p2.y - p.y, default_color)






More information about the Python-list mailing list