I would like to create a class that, when I call without the double brackets, returns a value in any context, just like what str or int does. For example, what can I do to make this possible:
>>> class color:
... def __init__(self, r, g, b):
... self.r = r
... self.g = g
... self.b = b
... def whatever_it_is(self):
... return (self.r, self.g, self.b) # Class returns tuple
>>> myColor = color(16, 32, 64)
>>> myColor.g
32
>>> myColor
(16, 32, 64)
>>> color(5, 68, 37)
(5, 68, 37)
My goal is to create a color class compatible with Pygame. For example, I could do mySurface.fill(color(16, 32, 64)), which would be the same as mySurface.fill((16, 32, 64)). My color class is like pygame.math.Vector2, but written in Python and not C.
As well as this, I have a bonus question that doesn't need to be answered: How do I make a class that can't be constructed?
Is this possible in Python 3.9?
Final edit: The answer below does not work fully. Here is what I mean:
>>> myColor = color(1, 2, 3)
>>> myColor
(1, 2, 3)
>>> myColor.g
2
>>> myColor.g = 4
>>> myColor
(1, 2, 3)
>>> myColor.g
4
I have found out about the __iter__ magic method and my highest priority was Pygame compatibility by converting a class to a tuple, so... ¯\_(ツ)_/¯
__init__method)thisClassto get a value without conversion usingtuple()and such.namedtupleincollections. Or make your class a sequence, like tuples are. But there's no magic method for what you're asking because how would you distinguish between when you're supposed to be accessing the instance and when the value it wraps?