Is there any way to get a class to return itself as tuple?


class _Desktop:
    def __init__(self):
        self._monitor = namedtuple(typename = 'Monitor', field_names = 'Width Height', defaults = GetMonitorInfo(MonitorFromPoint((0, 0))).get('Monitor')[2:])()  # noqa
        self._work = namedtuple(typename = 'Work', field_names = 'Width Height', defaults = GetMonitorInfo(MonitorFromPoint((0, 0))).get('Work')[2:])()  # noqa

    @property
    def Width(self):
        return self._monitor.Width

    @property
    def Height(self):
        return self._monitor.Height

    @property
    def Monitor(self):
        return self._monitor

    @property
    def Work(self):
        return self._work

Desktop = _Desktop()
print(Desktop)

Returns:__main__._Desktop object at 0x000001CAC4550590>

I want to set this up so when I put use Desktop it returns a tuple of Width, and Height

Do you mean you want to print like this?

Yeah, so desktop itself returns a tuple.

I know I can do this with __call__ but I want to leave out the round brackets and use Desktop like a variable.

Either Desktop is an instance of _Desktop or it is a named tuple but not both.

If you do this:

Then there is no point in the complexity of the _Desktop class.

Is this just about how it appears when you print it out? Or do you want a function that returns your class wrapped in a tuple?

For the former, you can define __str__ or __repr__ to make a nice readable representation of the class. For the latter, I would write a separate function (maybe a class method) to provide the output you need.

I got it figured out.

import collections
import win32api


class Monitor:
    def __init__(self):
        self._monitor = collections.namedtuple(typename = 'x', field_names = 'Width Height')(*win32api.GetMonitorInfo(win32api.MonitorFromPoint((0, 0))).get('Monitor')[2:])
        self._work = collections.namedtuple(typename = 'x', field_names = 'Width Height')(*win32api.GetMonitorInfo(win32api.MonitorFromPoint((0, 0))).get('Work')[2:])

    def __iter__(self):
        return iter(tuple(self._monitor))

    def __next__(self):
        return tuple(self._monitor)

    def __str__(self):
        return str(tuple(self._monitor))

    @property
    def Width(self) -> int:
        return self._monitor.Width

    @property
    def Height(self) -> int:
        return self._monitor.Height

    @property
    def WorkingArea(self):
        return self._work

Monitor = Monitor()

print(Monitor)
(3840, 1600)

print(3840 in Monitor)
True
2 Likes