rookie
rookie

Reputation: 2923

Python OOP: inefficient to put methods in classes?

I usually use classes similarly to how one might use namedtuple (except of course that the attributes are mutable). Moreover, I try to put lengthy functions in classes that won't be instantiated as frequently, to help conserve memory.

From a memory point of view, is it inefficient to put functions in classes, if it is expected that the class will be instantiated often? Keeping aside that it's good design to compartmentalize functionality, should this be something to be worried about?

Upvotes: 2

Views: 199

Answers (4)

lakshmen
lakshmen

Reputation: 29104

Each object has its own copy of data members whereas the the member functions are shared. The compiler creates one copy of the member functions separate from all objects of the class. All the objects of the class share this one copy.

The whole point of OOP is to combine data and functions together. Without OOP, the data cannot be reused, only the functions can be reused.

Upvotes: 2

chepner
chepner

Reputation: 532518

Instances of a class have one pointer that refers to the class; all other features of the class are unique and accessed through that pointer. Something like

foo.bar()

really translates to something like

foo.__class__.bar(foo)

so methods are unique, long-lived objects belonging to the class that take the instance as an argument when called.

Upvotes: 2

Jed Estep
Jed Estep

Reputation: 605

Python doesn't maintain pointers directly to its methods in instances of new-style classes. Instead, it maintains a single pointer to the parent class. Consider the following example:

class Foo:
  def bar(self):
    print 'hello'

f = Foo()
f.bar()

In order to dispatch the bar method from the instance f, two lookups need to be made. Instead of f containing a method table to look for bar, f contains a reference to the class object Foo. Foo contains the method table, where it calls bar with f as the first argument. So f.bar() can be rewritten as

Foo.bar(f)

Upvotes: 2

FatalError
FatalError

Reputation: 54641

Methods don't add any weight to an instance of your class. The method itself only exists once and is parameterized in terms of the object on which it operates. That's why you have a self parameter.

Upvotes: 6

Related Questions