When to use "property" builtin: auxiliary functions and generators

Posted by Seth Johnson on Stack Overflow See other posts from Stack Overflow or by Seth Johnson
Published on 2010-05-04T15:21:44Z Indexed on 2010/05/04 15:38 UTC
Read the original article Hit count: 328

Filed under:
|
|

I recently discovered Python's property built-in, which disguises class method getters and setters as a class's property. I'm now being tempted to use it in ways that I'm pretty sure are inappropriate.

Using the property keyword is clearly the right thing to do if class A has a property _x whose allowable values you want to restrict; i.e., it would replace the getX() and setX() construction one might write in C++.

But where else is it appropriate to make a function a property? For example, if you have

class Vertex(object):
    def __init__(self):
        self.x = 0.0
        self.y = 1.0

class Polygon(object):
    def __init__(self, list_of_vertices):
        self.vertices = list_of_vertices
    def get_vertex_positions(self):
        return zip( *( (v.x,v.y) for v in self.vertices ) )

is it appropriate to add

    vertex_positions = property( get_vertex_positions )

?

Is it ever ok to make a generator look like a property? Imagine if a change in our code meant that we no longer stored Polygon.vertices the same way. Would it then be ok to add this to Polygon?

    @property
    def vertices(self):
        for v in self._new_v_thing:
            yield v.calculate_equivalent_vertex()

© Stack Overflow or respective owner

Related posts about python

Related posts about best-practices