Reputation: 1727
In the realm of Python:
What can a class do that a function cannot, other than organizing code/design pattern?
Couldn't one technically write any class via functions? Not to say that it would be more efficient or readable but in terms of pure functionality.
Said differently, can someone take any class and rewrite it using only functions?
Upvotes: 1
Views: 200
Reputation: 155624
About the only largely unique, commonly used, features I can think of off-hand is that classes can be polymorphic, and classes can use operator overloading.
Nested functions using closure scope can do most of the stateful attribute things a class does by having each closure act as an "instance" with the function(s) defined in that closure scope sort of acting like methods, so in that sense, you could write really ugly code with "methods" sharing persistent state.
But runtime dynamic polymorphism isn't an option (you could choose different functions to return closing over that shared state, but it won't let you have polymorphic extensions in any sane way).
You also can't simulate existing types that overload operators; operator overloading must be done on the type, not the instance, and all user-defined functions share a single type which doesn't let you overload additional operators.
To be clear, there are things you can do with classes that are better done with functions. In particular, writing your own iterable and paired iterator classes is a pain, but generator functions can be used to make iterators with no classes at all, or to define the __iter__
of an iterable without needing to write the incredible ugliness that is a user-defined iterator class. Basically, they both exist, use the one that's clearly tailored for the situation at hand.
Upvotes: 7