views:

308

answers:

5

I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot...

Rather than just writing a procedure, would there be an benefits of using a Class? I can bury the actual analysis into functions so I can pass the data to the function and let it do it's thing but the functions are not contained in a Class.

What sort of drawbacks would a Class over come and what would be the purpose of using a Class if it can be written procedurally?

Thanks in advanced and if this has been posted before my apologies, just point me in that direction :)

+6  A: 

By using Object Oriented Programming, you will have objects, that have asociated functions, that are (should) be the only way to modify its properties (internal variables).

It was common to have functions called trim_string(string), while with a string class you could do string.trim(). The difference is noticeable mainly when doing big complex modules, where you need to do all you can to minify the coupling between individual components.

There are other concepts that encompass OOP, like inheritance, but the real important thing to know, is that OOP is about making you think about objects that have operations and message passing (methods/verbs), instead of thinking in term of operations (functions/verbs) and basic elements (variables)

The importance of the object oriented paradigm is not as much in the language mechanism as it is in the thinking and design process.

Alto take a look at this question.

There is nothing inherently wrong about Structured Programming, its just that some problems map better to an Object Oriented design.

For example you could have in a SP language:

#Pseudocode!!!

function talk(dog):
    if dog is aDog:
        print "bark!"
    raise "IS NOT A SUPPORTED ANIMAL!!!"

>>var dog as aDog
>>talk(dog)
"bark!"
>>var cat as aCat
>>talk(cat)
EXCEPTION: IS NOT A SUPPORTED ANIMAL!!!

# Lets add the cat
function talk(animal):
    if animal is aDog:
        print "bark!"
    if animal is aCat:
        print "miau!"
    raise "IS NOT A SUPPORTED ANIMAL!!!"

While on an OOP youd have:

class Animal:
     def __init__(self, name="skippy"):
         self.name = name
     def talk(self):
         raise "MUTE ANIMAL"

class Dog(Animal):
     def talk(self):
         print "bark!"

class Cat(Animal):
     def talk(self):
         print "miau!"

>>dog = new Dog()
>>dog.talk()
"bark!"
>>cat = new Cat()
>>cat.talk()
"miau!"

You can see that with SP, every animal that you add, you'd have to add another if to talk, add another variable to store the name of the animal, touch potentially every function in the module, while on OOP, you can consider your class as independent to the rest. When there is a global change, you change the Animal, when its a narrow change, you just have to look at the class definition.

For simple, secuencial, an possible throwaway code, its ok to use structured programming.

voyager
those are some very angry exceptions
mgroves
The user should be punished for doing something wrong. The interface should *hurt* the user. And security is **more important** than usability. In a perfect world, nobody would be able to use anything. http://www.usalyze.com/wp-content/dilbert-200209233.gif http://www.usernomics.com/images/dilbert.gif (didn't find all of the references)
voyager
+3  A: 

You don't need to use classes in Python - it doesn't force you to do OOP. If you're more comfortable with the functional style, that's fine. I use classes when I want to model some abstraction which has variations, and I want to model those variations using classes. As the word "class" implies, they're useful mainly when the stuff you are working with falls naturally into various classes. When just manipulating large datasets, I've not found an overarching need to follow an OOP paradigm just for the sake of it.

Vinay Sajip
+1  A: 

"but the functions are not contained in a Class."

They could be.

class Linear( object ):
    a= 2.
    b= 3.
    def calculate( self, somePoint ):
        somePoint['line']= b + somePoint['x']*a

class Exponential( object ):
    a = 1.05
    b = 3.2
    def calculate( self, somePoint ):
        somePoint['exp']= b * somePoint['x']**a

class Mapping( object ):
    def __init__( self ):
        self.funcs = ( Linear(), Exponential() )
    def apply( self, someData ):
        for row in someData:
            for f in self.funcs:
                f.calculate( row )

Now your calculations are wrapped in classes. You can use design patterns like Delegation, Composition and Command to simplify your scripts.

S.Lott
This is gross :-)
a paid nerd
Possibly. But it extends easily to create Composable analytic functions that you can configure fairly simply to do a wide variety of common slice/dice/analyze/summarize operations.
S.Lott
+1  A: 

OOP lends itself well to complex programs. It's great for capturing the state and behavior of real world concepts and orchestrating the interplay between them. Good OO code is easy to read/understand, protects your data's integrity, and maximizes code reuse. I'd say code reuse is one big advantage to keeping your frequently used calculations in a class.

Chris
+1  A: 
  • Object-oriented programming isn't the solution to every coding problem.

  • In Python, functions are objects. You can mix as many objects and functions as you want.

  • Modules with functions are already objects with properties.

  • If you find yourself passing a lot of the same variables around — state — an object is probably better suited. If you have a lot of classes with class methods, or methods that don't use self very much, then functions are probably better.

a paid nerd