python and tuple

Started by
3 comments, last by Oluseyi 15 years, 9 months ago
Is there a way I can get my own class to return a tuple to be use in a function automaticly. ex. x = myPoint(3,4) screen.blit(picture,mypoint) This works, but how do I remove the need to call the tuple function


screen.blit(picture, tuple(mypoint))


[Edited by - Zaris on July 4, 2008 12:56:30 PM]
Advertisement
Why do you need a class for points when a tuple is already a nearly ideal container for them? You're going to need to call some function to convert between the class and the tuple

class MyPoint:    def __init__(new_x, new_y):        x = new_x        y = new_y    def getTuple():        return (x, y)pos = MyPoint(4, 3)screen.blit(picture, pos.getTuple())


seriously, though...
pos = (4, 3)screen.blit(picture, pos)


Any functionality that you might get by methods of a point class can be done with free functions.
I'm trying to create a point class that will handled internally basic actions needed by a point or vector in a game. I want to be able to override the *,+, - operators and have a type conversion handled automaticly without an explict call to the class function.
I found a solution


 class Point(object):        def __init__(self, x, y):        self.x = x        self.y = y               def __getitem__(self, index):        li = [self.x,self.y]        try:            return li[index]        except IndexError:            raise IndexError, "incorrect arg"    def __len__(self):        return 2


I just needed to set up a function to return the length of the object.
Yeah, you don't actually need to return a tuple, you merely need for your type to behave like a tuple. You'll find this often in Python, where constructs don't depend on explicit type information, but rather on interfaces and conformance to a concept.

This topic is closed to new replies.

Advertisement