How to decide when to introduce a new type instead of using a list or tuple?

I like to do some silly things with python, like solving programming puzzles, writing small scripts, etc. Each time I come across a dilemma at some point, should I create a new class to represent my data or just use the fast and dirty ones and come with all the values ​​packed into a list or tuple. Due to extreme laziness and personal hostility to the keyword, selfI usually move on to the second option.

I understand that in the end, the user data type is better, because path.min_costboth are point.x, point.ymuch more expressive than path[2]and point[0], point[1]. But when I just need to return a few things from a function, it seems to me that this is too much work.

So my question is what is a good rule for choosing when to create a custom data type and when to go with a list or tuple? Or maybe there is a neat pythonic way that I don't know about?

Thank.

+5
source share
3 answers

-, . point.x, point.y vs. point[0], point[1], , . , point, , , , :

x, y = get_point(foo)

, , point.x, point.y; , , ( , - __dict__), , .

, - , , : : " ?" , , , , , , , , . , , , , , , , , .

, , ; , , - , , 15 ( namdetuple). , , , , .

+2

collections.namedtuple? ( 2.6)

def getLocation(stuff):
    return collections.namedtuple('Point', 'x, y')(x, y)

, ,

Point = collections.namedtuple('Point', 'x, y')
def getLocation(stuff):
    return Point(x, y)

namedtuple (point[0]) (x, y = point) , tuple, .

+8

, , , .

(, point.x point.y ), .

( return min, max), .

+2
source

All Articles