Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create custom data type in 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

I am not sure what you want to do with the tuple. p will always be an instance of Point. What you intend to do there won’t work.

If you just don’t want to use the dot notation, you could use a namedtuple or a dataclass instead of a class. Then cast their instances to a tuple using tuple() and astuple().


Using a namedtuple and tuple():

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])

p = Point(4, 5)

x = p.x
y = p.y

xy = tuple(p)

Note: namedtuple is immutable, i.e. you can’t change x and y.


Using a dataclasses.dataclass and dataclasses.astuple():

from dataclasses import dataclass, astuple

@dataclass
class Point:
    x: int
    y: int
    
p = Point(4, 5)

x = p.x
y = p.y

xy = astuple(p)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading