[Python] Create custom data type in Python

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    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!

    Continue reading...

Compartilhe esta Página