12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

You’ll also see another _ _call_ _ example in Chapter 26, where we will use it toimplement something known as a function decorator—a callable object that adds alayer of logic on top of an embedded function. Because _ _call_ _ allows us to attachstate information to a callable object, it’s a natural implementation technique for afunction that must remember and call another function._ _del_ _ <strong>Is</strong> a DestructorThe _ _init_ _ constructor is called whenever an instance is generated. Its counterpart,the destructor method _ _del_ _, is run automatically when an instance’s spaceis being reclaimed (i.e., at “garbage collection” time):>>> class Life:... def _ _init_ _(self, name='unknown'):... print 'Hello', name... self.name = name... def _ _del_ _(self):... print 'Goodbye', self.name...>>> brian = Life('Brian')Hello Brian>>> brian = 'loretta'Goodbye BrianHere, when brian is assigned a string, we lose the last reference to the Life instance,and so trigger its destructor method. This works, and it may be useful for implementingsome cleanup activities (such as terminating server connections). However,destructors are not as commonly used in <strong>Python</strong> as in some OOP languages, for anumber of reasons.For one thing, because <strong>Python</strong> automatically reclaims all space held by an instancewhen the instance is reclaimed, destructors are not necessary for space management. *For another, because you cannot always easily predict when an instance will bereclaimed, it’s often better to code termination activities in an explicitly calledmethod (or try/finally statement, described in the next part of the book); in somecases, there may be lingering references to your objects in system tables that preventdestructors from running.That’s as many overloading examples as we have space for here. Most of the otheroperator overloading methods work similarly to the ones we’ve explored, and all arejust hooks for intercepting built-in type operations; some overloading methods, forexample, have unique argument lists or return values. You’ll see a few others inaction later in the book, but for complete coverage, I’ll defer to other documentationsources.* In the current C implementation of <strong>Python</strong>, you also don’t need to close file objects held by the instance indestructors because they are automatically closed when reclaimed. However, as mentioned in Chapter 9, it’sbetter to explicitly call file close methods because auto-close-on-reclaim is a feature of the implementation,not of the language itself (this behavior can vary under Jython).Operator Overloading | 505

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!