Saturday, February 5, 2011

Does Python have properties?

So something like:

vector3.Length

that's in fact a function call that calculates the length of the vector, not a variable.

  • If your variable vector3 is a 3-dimensional directed distance of a point from an origin, and you need its length, use something like:

    import math
    vector3 = [5, 6, -7]
    print math.sqrt(vector3[0]**2 + vector3[1]**2 + vector3[2]**2)
    

    If you need a solution which works for any number of dimensions, do this:

    import math
    vector3 = [5, 6, -7]
    print math.sqrt(sum(c ** 2 for c in vector3))
    

    You can define your own vector class with the Length property like this:

    import math
    class Vector3(object):
      def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
      @property
      def Length(self):
        return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
    vector3 = Vector3(5, 6, -7)
    print vector3.Length
    
    From pts
  • Yes: http://docs.python.org/library/functions.html#property

    From S.Lott
  • With new-style classes you can use property(): http://www.python.org/download/releases/2.2.3/descrintro/#property.

  • Before the property() decorator came in, the idiom was using a no-parameter method for computed properties. This idiom is still often used in preference to the decorator, though that might be for consistency within a library that started before new-style classes.

    From Sii
  • you can override some special methods to change how attributes are accesss, see the python documentation here or here

    Both these will slow down any attribute access to your class however, so in general using properties is probably best.

0 comments:

Post a Comment