Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom data type in Python

Tags:

python

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!

like image 813
AwoeDace Avatar asked May 06 '26 18:05

AwoeDace


1 Answers

Python 3.12+

PEP 695 introduces a new, more compact and explicit way to create generic classes and functions. In addition, the PEP introduces a new way to declare type aliases using the type statement, which creates an instance of TypeAliasType. As a result, you can do this:

type Point = tuple[float, float]
# or
type Point[T] = tuple[T, T] # more generic

For example, you can use it like this:

type Point = tuple[int, int]
p: Point = (0,0)
print(p) # (0,0)

p = (4,5) # re-assign Point p
print(p[0]) # 4, your "x" 
print(p[1]) # 5, your "y"

Depending on your use case, this answer may not be relevant.

like image 166
LHY Avatar answered May 11 '26 04:05

LHY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!