473,406 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

automatically assigning names to indexes

I know its been done before, but I'm hacking away on a simple Vector
class.

class Vector(tuple):
def __add__(self, b):
return Vector([x+y for x,y in zip(self, b)])
def __sub__(self, b):
return Vector([x-y for x,y in zip(self, b)])
def __div__(self, b):
return Vector([x/b for x in self])
def __mul__(self, b):
return Vector([x*b for x in self])

I like it, because it is simple, and can work with vectors of any
size...

However, I'd like to add attribute access (magically), so I can do
this:

v = Vector((1,2,3))
print v.x
print v.y
print v.z

as well as:

print v[0]
print v[1]
print v[2]

Has anyone got any ideas on how this might be done?
Sw.

Jul 21 '05 #1
8 1374
si**********@gmail.com wrote:
However, I'd like to add attribute access (magically), so I can do
this:

v = Vector((1,2,3))
print v.x
print v.y
print v.z

as well as:

print v[0]
print v[1]
print v[2]

Has anyone got any ideas on how this might be done?

class Vector(tuple): .... x = property(lambda self: self[0])
.... y = property(lambda self: self[1])
.... z = property(lambda self: self[2])
.... Vector("abc") ('a', 'b', 'c') Vector("abc").z 'c' Vector("abc")[2]

'c'

However, no magic is involved.

Peter

Jul 21 '05 #2
> >>> class Vector(tuple):
... x = property(lambda self: self[0])
... y = property(lambda self: self[1])
... z = property(lambda self: self[2])
...
Vector("abc") ('a', 'b', 'c') Vector("abc").z 'c' Vector("abc")[2]

'c'


Aha! You have simultaneously proposed a neat solution, and shown me a
bug in my class! (It shouldn't accept strings)

Thanks.

Sw.

Jul 21 '05 #3
<si**********@gmail.com> wrote:
I know its been done before, but I'm hacking away on a simple Vector
class.

class Vector(tuple):
def __add__(self, b):
return Vector([x+y for x,y in zip(self, b)])
def __sub__(self, b):
return Vector([x-y for x,y in zip(self, b)])
def __div__(self, b):
return Vector([x/b for x in self])
def __mul__(self, b):
return Vector([x*b for x in self])

I like it, because it is simple, and can work with vectors of any
size...

However, I'd like to add attribute access (magically), so I can do
this:

v = Vector((1,2,3))
print v.x
print v.y
print v.z

as well as:

print v[0]
print v[1]
print v[2]

Has anyone got any ideas on how this might be done?


And what should happen for vectors of size != 3 ? I don't think that a
general purpose vector class should allow it; a Vector3D subclass would
be more natural for this.

George

Jul 21 '05 #4
[si**********@gmail.com]
I know its been done before, but I'm hacking away on a simple Vector
class. [...] However, I'd like to add attribute access (magically),
so I can do this: [...] Has anyone got any ideas on how this might be
done?


I needed something this last week, while toying with rotations. Allow
me to humbly offer my solution, meant for more than one class. Yet for
brievety, I'm limiting my example to a single class. A few constructors
are used in the example, but the corresponding classes are missing.

I hesitated a bit between having my rotation objects be modifiable or
not, and finally opted for the later (consequently, the constructor is
neatly called for a resulting object). If you really want a modifiable
object, derive from `list' instead of deriving from `tuple', rename
`NamedTuple' into `NamedList', and wihin sub-classes, initialise your
object with `__init__(self, ...)' rather than with `__new__(cls, ...)'.

__metaclass__ = type
import math

# Almost zero, but not yet.
epsilon = 1e-9

from math import pi
half_pi = .5*pi

class NamedTuple(tuple):

class __metaclass__(type):

def __new__(cls, name, bases, definitions):
self = type.__new__(cls, name, bases, definitions)
if hasattr(self, '__names__'):
def make_property(index):
def getter(self): return self[index]
return property(getter)
for index, name in enumerate(self.__names__):
setattr(self, name, make_property(index))
return self

class Quaternion(NamedTuple):
__names__ = 'w', 'x', 'y', 'z'

def __new__(cls, w, x, y, z):
l = 1./math.sqrt(w*w + x*x + y*y + z*z)
return cls.new(w*l, x*l, y*l, z*l)

def new(cls, w, x, y, z):
if w < 0.:
self = tuple.__new__(cls, (-w, -x, -y, -z))
else:
self = tuple.__new__(cls, (w, x, y, z))
assert self.is_normal(), self
return self
new = classmethod(new)

def is_normal(self):
# For debugging only.
w, x, y, z = self
return abs(w*w + x*x + y*y + z*z - 1.) < epsilon and w >= 0.

def __eq__(self, other):
w1, x1, y1, z1 = self
w2, x2, y2, z2 = other
return abs(w1-w2) + abs(x1-x2) + abs(y1-y2) + abs(z1-z2) < epsilon

def __ne__(self, other):
return not self == other

def __mul__(self, other):
w1, x1, y1, z1 = self
w2, x2, y2, z2 = other
return Quaternion.new(w1*w2 - x1*x2 - y1*y2 - z1*z2,
w1*x2 + x1*w2 + y1*z2 - z1*y2,
w1*y2 + y1*w2 - x1*z2 + z1*x2,
w1*z2 + z1*w2 + x1*y2 - y1*x2)

def __div__(self, other):
w1, x1, y1, z1 = self
w2, x2, y2, z2 = other
return Quaternion.new( w1*w2 + x1*x2 + y1*y2 + z1*z2,
-w1*x2 + x1*w2 - y1*z2 + z1*y2,
-w1*y2 + y1*w2 + x1*z2 - z1*x2,
-w1*z2 + z1*w2 - x1*y2 + y1*x2)

def __rdiv__(self, other):
if not isinstance(other, (int, long, float)):
raise TypeError("unsupported operand type(s) for /")
w, x, y, z = self
return Quaternion.new(w, -x, -y, -z)

__truediv__ = __div__
__rtruediv__ = __rdiv__

def euler(self):
w, x, y, z = self
x2 = x + x
y2 = y + y
z2 = z + z
xx2 = x2*x
yy2 = y2*y
zz2 = z2*z
wx2 = x2*w
wy2 = y2*w
wz2 = z2*w
xy2 = x2*y
yz2 = y2*z
zx2 = z2*x
siny = wy2 - zx2
if abs(abs(siny) - 1) > epsilon:
return Euler.new(math.asin(siny),
math.atan2(yz2 + wx2, 1. - xx2 - yy2),
math.atan2(xy2 + wz2, 1. - yy2 - zz2))
if siny > 0.:
y = half_pi
else:
y = -half_pi
return Euler.new(math.atan2(-(yz2 - wx2), 1. - xx2 - zz2), y, 0.)

def matrix(self):
w, x, y, z = self
x2 = x + x
y2 = y + y
z2 = z + z
xx2 = x2*x
yy2 = y2*y
zz2 = z2*z
wx2 = x2*w
wy2 = y2*w
wz2 = z2*w
xy2 = x2*y
yz2 = y2*z
zx2 = z2*x
return Matrix(1. - yy2 - zz2, xy2 + wz2, zx2 - wy2,
xy2 - wz2, 1. - xx2 - zz2, yz2 + wx2,
zx2 + wy2, yz2 - wx2, 1. - xx2 - yy2)

--
François Pinard http://pinard.progiciels-bpi.ca
Jul 21 '05 #5
And what should happen for vectors of size != 3 ? I don't think that a
general purpose vector class should allow it; a Vector3D subclass would
be more natural for this.


That's the 'magic' good idea I'm looking for. I think a unified Vector
class for all size vectors is a worthy goal!

Jul 21 '05 #6
<si**********@gmail.com> wrote
And what should happen for vectors of size != 3 ? I don't think that a
general purpose vector class should allow it; a Vector3D subclass would
be more natural for this.


That's the 'magic' good idea I'm looking for. I think a unified Vector
class for all size vectors is a worthy goal!


What 'magic' ? The (x,y,z) notation is used only for 3D vectors. (x,y)
is also common for 2D and perhaps (t,x,y,z) for 4D, with t for time.
There are only 26 letters (or 52 if you allow capitals), so I don't see
how this can be generalized _usefully_ to arbitrary number of
dimensions.

George

Jul 21 '05 #7
import math
class Vector:
def __init__(self, coordinates):
self.coordinates = coordinates
self.magnitude = sum([c**2 for c in coordinates])**0.5
self.direction = getangle(Vector([1]+[0 for i in
range(len(coordinates)-1)]))
def dotproduct(self, vector):
sum([a*b for a,b in zip(self.coordinates,vector.coordinates)])
def crossproduct(self, vector, pvector):
return
pvector*self.magnitude*vector.magnitude*math.sin(s elf.getangle(vector))
def getangle(self, vector):
return
math.acos(self.dotproduct(vector)/(self.magnitude*vector.magnitude))
def __mul__(self, scalar):
return Vector([c*scalar for c in self.coordinates])
def __add__(self, vector):
return Vector([c+d for c,d in
zip(self.coordinates,vector.coordinates)])
def __sub__(self, vector):
return Vector([c-d for c,d in
zip(self.coordinates,vector.coordinates)])

What about this?

Jul 21 '05 #8

George> What 'magic' ? The (x,y,z) notation is used only for 3D
George> vectors. (x,y) is also common for 2D and perhaps (t,x,y,z) for
George> 4D, with t for time.

Don't forget (w,x,y,z) for quaternions...

Skip
Jul 21 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Ben | last post by:
Hi all, This may sound easy but I'm having trouble assigning values to array element. My problem is as follows: m = for o in m: # Here first o is 'Peter'.. I want to do something like this:...
4
by: Matt | last post by:
Hi all, We recently upsized two Microsoft Access Databases to SQL. We're using an ADP (2002) as the front end. All the conversion issues have been resolved, except for one: Whenever we...
3
by: mfyahya | last post by:
I have a table `books` with booktitle and authorname columns. In my applicatoin booktitle has unique values but authorname doesn't. ie an author can have many books but not the other way around. ...
13
by: gary | last post by:
Hi, We all know the below codes are dangerous: { int *p = new int; delete p; delete p; } And we also know the compilers do not delete p if p==NULL. So why compilers do not "p = NULL"...
0
by: Tom Warren | last post by:
I found a c program called similcmp on the net and converted it to vba if anybody wants it. I'll post the technical research on it if there is any call for it. It looks like it could be a useful...
6
by: HD | last post by:
Hello. For the following, I would appreciate if anyone could tell me: if it can be done, how it might done, and/or what search terms I could use to find the solution myself. I would like to...
0
by: Mythran | last post by:
I wrote some code that is supposed to enumerate through the specified file's win32 resources and return a string-array of all icon names. When it runs, it returns a string-array with a bunch of...
5
by: jacob.dba | last post by:
I have a table with first name, last name, SSN(social security number) and other columns. I want to assign group number according to this business logic. 1. Records with equal SSN and (similar...
111
by: Nate | last post by:
Hello, I am looking for a method to automatically declare variables in C. I'm not sure if there is a good way to do this, but I had something like this in mind... int i; for(i = 1; i < 4;...
1
by: tsorgi | last post by:
I'm writing a data conversion application to support a system migration. The code is reading formatted text files and loading them into MS SQL 2005 database tables. I wanted to call the existing...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.