Joan Venge
Joan Venge

Reputation: 330872

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.

Upvotes: 3

Views: 440

Answers (5)

bill donner
bill donner

Reputation:

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.

Upvotes: 0

millimoose
millimoose

Reputation: 39950

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.

Upvotes: 3

pts
pts

Reputation: 87201

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

Upvotes: 5

Bastien Léonard
Bastien Léonard

Reputation: 61683

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

Upvotes: 14

Related Questions