1

I was always wondering about two things I tend to do in my little projects. Sometimes I will have this design:

class FooClass
 ...
 self.foo = "it's a bar"
 self._do_some_stuff(self)
 def _do_some_stuff(self):
 print(self.foo)

And sometimes this one:

class FooClass2
 ...
 self.do_some_stuff(foo="it's a bar")
 def do_some_stuff(self, foo):
 print(foo) 

Although I roughly understand the differences between functional and class approaches, I struggle with the design.

For example, in FooClass the self.foo is always accessible as an attribute. If there are numerous calls to it, is that faster than making foo a local variable that is passed from method to method (like in FooClass2)? What happens in memory in both cases?

If FooClass2 is preferred (ie. I don't need to access foo) and other attributes inside do not change their states (the class is executed once only and returns the result), should the code then be written as a series of functions in a module?

asked Jun 24, 2011 at 21:33

1 Answer 1

1

Both approaches are going to be roughly equivalent in speed, depending on optimizations, architecture, what memory was previously cached, etc. I wouldn't concern myself with speed unless profiling deems it critical.

The design principle in play here is you want variables to stick around as long as they are needed, and no longer. This avoids problems like thinking foo already contains the value you want, but it's actually old data that just happens to pass your tests, but fails miserably in production. That means the second approach is generally preferable unless you have a good reason to keep foo around for longer than one function call, and if the current object is the most logical place to keep it.

answered Jun 24, 2011 at 22:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.