Hopefully the title isn't too misleading, I'm not sure the best way to phrase my question.
I'm trying to create a (X, Y) coordinate data type in Python. Is there a way to create a "custom data type" so that I have an object with a value, but also some supporting attributes?
So far I've made this simple class:
class Point: def __init__(self, x, y): self.x = x self.y = y self.tuple = (x, y) Ideally, I'd like to be able to do something like this:
>>> p = Point(4, 5) >>> >>> my_x = p.x # can access the `x` attribute with "dot syntax" >>> >>> my_tuple = p # or can access the tuple value directly # without needing to do `.tuple`, as if the `tuple` # attribute is the "default" attribute for the object NOTE I'm not trying to simply display the tuple, I know I can do that with the __repr__ method
In a way, I'm trying to create a very simplified numpy.ndarray, because the ndarrays are a datatype that have their own attributes. I tried looking thru the numpy source to see how this is done, but it was way over my head, haha.
Any tips would be appreciated!
tupleattribute because then you have to worry about keeping data in sync if x, y or the tuple itself change. Do you want to perform operations on the class as a whole, or just have a convenient place to park x and y? Are these mutable or immutable? As stands, the class already does what you want. We need to know what problem you are having.my_tuple = paccessing "tuple directly without needing to do.tuple", I can't think of a way this is possible. The statementmy_tuple = pdefines a new reference to an object, which could be any python object in principle.collections.namedtuplemay be what you want. Review it, and let us know how it doesn't work for you.namedtupledoes it. You can access its values asp.xorp[0]. It even works withisinstance(p, tuple). You don't need themy_tuple = ppart, though. As you say, all that does is add a ref count to the existing object.Pointwas a somewhat simplified example of what I’m dealing with, but overall I think I’m over-engineering this piece in attempt to make my code cleaner (which has backfired haha). I think I’ll try to use the namedtuple as suggest by @Thomas