9 ms·
I almost never write classes in Python. That may be a result of the fact that I never use Python for anything other than system automation and data post process
by scott_s 15y ago
I almost never write classes in Python. That may be a result of the fact that I never use Python for anything other than system automation and data post processing; I don't use Python to build complicated systems. What I have made use of are named tuples:
3DPoint = collections.namedtuple('3DPoint', ['x', 'y', 'z'])
p1 = 3DPoint(3, 2, 4)
p2 = 3DPoint(10, 1, 10)
dist = math.sqrt((p2.x - p1.x)**2 +
(p2.y - p1.y)**2 +
(p2.z - p1.z)**2)
I don't mean to say that classes aren't useful in Python, just that I've gotten a lot done in the language just depending on hashes, lists, tuples, named tuples, functions, comprehensions and generators. I've never felt the need to define a a class - the closest I came, I realized I wanted a named tuple. It certainly would make sense in the above example to define "dist" as a member function of a 3DPoint class, but it's just not how I write code in Python.
Contrast this with C++, where I define classes all the time. I think the reason for this discrepancy is that if you want to do anything interesting in C++, you almost have to define a struct or a class; that's where most of the abstractions happen. In fact, if I want functional style code in C++, I have to define my functions as classes. I think that Python's native tuple types, first-class functions and comprehensions make the difference.
- quotemstr 15y ago> if I want functional style code in C++, I have to define my functions as classes Much of the benefit of C++11 and Boost is in not having to write functor classes.
- scott_s 15y agoLambdas buy us this in C++11 (which is awesome), but not so much with Boost alone. Boost can help if you are, say, applying the member function of a class to a bunch of objects; you don't have to write a speciality function object to express that. But if you're writing logic from scratch, and you want it to be a closure, it needs to be a function object.
- quotemstr 15y agoYes, but many function objects can be constructed easily enough with Boost.Lambda and related libraries.
- scott_s 15y agoOy, Boost.Lambda. I tried, I really tried. I wrote this comment here on HN a year and a half ago: I played with boost::lambda, and I found the resulting code less clear than a simple for loop. I also had difficulty gaining an intuition for what I could and could not do with it. Rather than constantly asking myself "Can I use boost::lambda here...? Will it look better or worse than the alternative?" I just decided to never use it. While I prefer a functional style of coding, I recognized that it was silly to adhere to it if doing so made my code worse - C++'s support for what I wanted to do just wasn't there. If what I wanted to accomplish was several lines of code, I wrote a separate function or function object. If it was brief and I could not express it with combinations of existing functions, then I just wrote a for loop.
- SamReidHughes 15y agoIf you're writing the logic from scratch and want a function object, make a function whose arguments are the variables you need to close over and then use boost::bind. That's the most convenient way.
- swah 15y agoI would love to use other languages (static ones), but Python is so pragmatic AND still on an upward trend right now that it would be stupid for me not to use it.
- dkhenry 15y agothe PyCAM codebase has this exact change made to is and it decreased the run time significantly. That's another thing that I didn't see mentioned in the lecture. Python classes are not free they have a definite impact on performance.
- gruseom 15y agoA few years ago, I quit organizing my code in terms of classes altogether. Everything got so much simpler that for me that whole way of looking at programming is now a gigantic mistake. It's true that you have to have a powerful enough language to get away with writing only functions, or at least one that doesn't impose classes on you, but that's true of lots of languages nowadays. Freud said sometimes a cigar is only a cigar. I say sometimes a function is only a function. Classes get in the way between the programmer and the problem. They force you to reify your thinking into "things" (classes) that demand names and citizenship rights, so to speak, in the system. These "things" don't really exist, but we act like they do, and so increasingly see the problem in terms of the classes we've defined. This is a distorting filter that we can ill afford when the problem is complex (if it's not complex, who cares - anything will work ok). The solution is not to define such pseudo-things in the first place, but rather to focus at all times on the problem at hand. Functions, for me, are the right level of abstraction to do this. They don't get in the way. Once a bunch of classes have taken residence in your system and your brain, it's hard to remember that they aren't real, and thus the pain threshold is quite high before you realize that they're causing problems. At that point they're hard to change: you have to replace the old class hierarchy with a new class hierarchy. The difference between that and reworking a few functions is the difference between working in concrete and clay. There's also the cognitive tax of having to think about what classes to create and what to name them. This too is overhead we can ill afford given our limited mental resources. If you've ever found yourself putting some code in a new class (perhaps because the old one got too big, or because you need to use it from two places) and gotten stopped in your tracks by the question, "What should I name it? What is this thing?" you are experiencing the overhead I'm talking about. It's the programming equivalent of Mr. Heavyfoot: http://www.youtube.com/watch?v=R9d2Y1We-d0 http://www.youtube.com/watch?v=R9d2Y1We-d0. There is no such thing; you're just working in a way that forces you to pretend that there is and fulfill a bunch of duties towards it. These two issues together are a double-whammy: you pay up front for what you pay for later. It is shocking to see how much simpler systems become when we stop doing the things that make them complicated.
- pnathan 15y agoI have a similar approach. I only use classes when I find myself passing around an object that is starting looking suspiciously class-like. While this adds a refactoring burden, it turns out most of the time, OO is a waste of time, and a few arguments is all you need. Some things are objects, in and of their nature. So it turns out that they transform into classes very nicely. But most of the time, you have data, and you have things that work on that data, and it really does you no good to nounize the world too far. You wind up going off into this ontological modelling foolishness, and as a rule of thumb, you wasted your time.
- jnbiche 15y agoI really like this approach. Plus, it's easy to parse, particularly if you use class name capitalization for the named tuple (like you did). I've seen this done before, but after your reminder, I resolve to start using named tuples where before I sometimes gratuitously used classes. They probably perform much better than classes, too (although I'll probably benchmark just to be sure).
- mikepurvis 15y agoI'm a huge fan of a namedtuple; I'm always surprised not to see it used more. And in cases where you really do need class-like behaviour, it's easy to extend it with additional methods or operators, while still getting all the other convenience stuff for free: class Point3D(namedtuple('Point3D', "x y z")): def __add__(self, other): if other.__class__ != self.__class__: raise TypeError return self.__class__(*[a+b for a,b in zip(self, other)]) print Point3D(1, 2, 3) + Point3D(5, 4, 2)
- kisielk 15y agoBeware that once you subclass namedtuple you are losing out on one of its beneficial characteristics: memory efficiency. Instances of subclasses have an instance dict which has a non-trivial overhead. You can avoid this by defining __slots__ again in the subclass.