Text stringlengths 1 9.41k |
|---|
By allowing us to encapsulate behavior,
it also allows us to factor that code to avoid redundancy and its associated maintenance
headaches.
The only major OOP concept it does not yet capture is customization by inheritance.
In some sense, we’re already doing inheritance, because instances inherit methods from
their cl... |
To demonstrate the real power of OOP, though, we need to define a
superclass/subclass relationship that allows us to extend our software and replace bits
of inherited behavior. |
That’s the main idea behind OOP, after all; by fostering a coding
model based upon customization of work already done, it can dramatically cut development time.
###### Coding Subclasses
As a next step, then, let’s put OOP’s methodology to use and customize our Person
class by extending our software hierarchy. |
For the purpose of this tutorial, we’ll define
a subclass of Person called Manager that replaces the inherited giveRaise method with
a more specialized version. |
Our new class begins as follows:
```
class Manager(Person): # Define a subclass of Person
```
This code means that we’re defining a new class named Manager, which inherits from
and may add customizations to the superclass Person. |
In plain terms, a Manager is almost
**|**
-----
like a Person (admittedly, a very long journey for a very small joke...), but Manager has
a custom way to give raises.
For the sake of argument, let’s assume that when a Manager gets a raise, it receives the
passed-in percentage as usual, but also gets an extra bonus... |
For
instance, if a Manager’s raise is specified as 10%, it will really get 20%. |
(Any relation to
```
Persons living or dead is, of course, strictly coincidental.) Our new method begins as
```
follows; because this redefinition of `giveRaise will be closer in the class tree to`
```
Manager instances than the original version in Person, it effectively replaces, and thereby
```
customizes, the oper... |
Recall that according to the inheritance search rules, the
_lowest version of the name wins:_
```
class Manager(Person): # Inherit Person attrs
def giveRaise(self, percent, bonus=.10): # Redefine to customize
###### Augmenting Methods: The Bad Way
```
Now, there are two ways we might code this Mana... |
Let’s start with the bad way, since it might be a bit easier to understand. |
The
bad way is to cut and paste the code of giveRaise in Person and modify it for Manager,
like this:
```
class Manager(Person):
def giveRaise(self, percent, bonus=.10):
self.pay = int(self.pay * (1 + percent + bonus)) # Bad: cut-and-paste
```
This works as advertised—when we later call the giveRaise meth... |
So what’s wrong
with something that runs correctly?
The problem here is a very general one: any time you copy code with cut and paste,
you essentially double your maintenance effort in the future. |
Think about it: because
we copied the original version, if we ever have to change the way raises are given (and
we probably will), we’ll have to change the code in two places, not one. |
Although this
is a small and artificial example, it’s also representative of a universal issue—any time
you’re tempted to program by copying code this way, you probably want to look for a
better approach.
###### Augmenting Methods: The Good Way
What we really want to do here is somehow augment the original giveRaise,... |
The good way to do that in Python is by calling to the original
version directly, with augmented arguments, like this:
```
class Manager(Person):
def giveRaise(self, percent, bonus=.10):
Person.giveRaise(self, percent + bonus) # Good: augment original
```
**|**
-----
This code leverages the fact th... |
In more symbolic terms, recall that a normal method call of this
form:
```
instance.method(args...)
```
is automatically translated by Python into this equivalent form:
```
class.method(instance, args...)
```
where the class containing the method to be run is determined by the inheritance search
rule applied to t... |
You can code either form in your script, but there
is a slight asymmetry between the two—you must remember to pass along the instance
manually if you call through the class directly. |
The method always needs a subject
instance one way or another, and Python provides it automatically only for calls made
through an instance. |
For calls through the class name, you need to send an instance to
```
self yourself; for code inside a method like giveRaise, self already is the subject of the
```
call, and hence the instance to pass along.
Calling through the class directly effectively subverts inheritance and kicks the call
higher up the class tr... |
In our case, we can use this technique
to invoke the default `giveRaise in` `Person, even though it’s been redefined at the`
`Manager level. |
In some sense, we` _must call through_ `Person this way, because a`
```
self.giveRaise() inside Manager’s giveRaise code would loop—since self already is a
Manager, self.giveRaise() would resolve again to Manager.giveRaise, and so on and so
```
forth until available memory is exhausted.
This “good” version may seem l... |
And really, this form captures our intent more directly anyhow—we want to
perform the standard giveRaise operation, but simply tack on an extra bonus. |
Here’s
our entire module file with this step applied:
_# Add customization of one behavior in a subclass_
```
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
def lastName(self):
return self.name.split()[-1]
def giveRaise(self... |
Here’s the new version’s output:
```
[Person: Bob Smith, 0]
[Person: Sue Jones, 100000]
Smith Jones
[Person: Sue Jones, 110000]
Jones
[Person: Tom Jones, 60000]
```
Everything looks good here: bob and sue are as before, and when tom the Manager is
given a 10% raise, he really gets 20% (his pay goes from $5... |
Also notice how printing tom as a
whole at the end of the test code displays the nice format defined in Person’s __str__:
```
Manager objects get this, lastName, and the __init__ constructor method’s code “for
```
free” from Person, by inheritance.
###### Polymorphism in Action
To make this acquisition of inherited ... |
Trace the method calls yourself to see how Python selects the right giveRaise method for each object.
This is just Python’s notion of polymorphism, which we met earlier in the book, at work
again—what giveRaise does depends on what you do it to. |
Here, it’s made all the more
obvious when it selects from code we’ve written ourselves in classes. |
The practical effect
in this code is that `sue gets another 10% but` `tom gets another 20%, because`
```
giveRaise is dispatched based upon the object’s type. |
As we’ve learned, polymorphism
```
is at the heart of Python’s flexibility. |
Passing any of our three objects to a function that
calls a giveRaise method, for example, would have the same effect: the appropriate
version would be run automatically, depending on which type of object was passed.
On the other hand, printing runs the same `__str__ for all three objects, because it’s`
coded just onc... |
Manager both specializes and applies the code we originally
wrote in Person. |
Although this example is small, it’s already leveraging OOP’s talent
for code customization and reuse; with classes, this almost seems automatic at times.
###### Inherit, Customize, and Extend
In fact, classes can be even more flexible than our example implies. |
In general, classes
can inherit, customize, or extend existing code in superclasses. |
For example, although
we’re focused on customization here, we can also add unique methods to Manager that
are not present in Person, if Managers require something completely different (Python
namesake reference intended). |
The following snippet illustrates. |
Here, giveRaise redefines a superclass method to customize it, but someThingElse defines something new
to extend:
```
class Person:
def lastName(self): ...
def giveRaise(self): ...
def __str__(self): ...
class Manager(Person): # Inherit
def giveRaise(self, ...): ... |
# Customize
def someThingElse(self, ...): ... |
# Extend
tom = Manager()
tom.lastName() # Inherited verbatim
tom.giveRaise() # Customized version
tom.someThingElse() # Extension here
print(tom) # Inherited overload method
```
Extra methods like this code’s someThingElse _extend the existing softw... |
For the purposes of this tutorial, however,
**|**
-----
we’ll limit our scope to customizing some of Person’s behavior by redefining it, not
adding to it.
###### OOP: The Big Idea
As is, our code may be small, but it’s fairly functional. |
And really, it already illustrates
the main point behind OOP in general: in OOP, we program by customizing what has
already been done, rather than copying or changing existing code. |
This isn’t always an
obvious win to newcomers at first glance, especially given the extra coding requirements
of classes. |
But overall, the programming style implied by classes can cut development
time radically compared to other approaches.
For instance, in our example we could theoretically have implemented a custom
```
giveRaise operation without subclassing, but none of the other options yield code as
```
optimal as ours:
- Althoug... |
As usual, the cut-and-paste approach may seem`
quick now, but it doubles your work in the future.
The customizable hierarchies we can build with classes provide a much better solution
for software that will evolve over time. |
No other tools in Python support this development mode. |
Because we can tailor and extend our prior work by coding new subclasses,
we can leverage what we’ve already done, rather than starting from scratch each time,
breaking what already works, or introducing multiple copies of code that may all have
to be updated in the future. |
When done right, OOP is a powerful programmer’s ally.
###### Step 5: Customizing Constructors, Too
Our code works as it is, but if you study the current version closely, you may be struck
by something a bit odd—it seems pointless to have to provide a `mgr job name for`
```
Manager objects when we create them: this is... |
It would
```
be better if we could somehow fill in this value automatically when a Manager is made.
The trick we need to improve on this turns out to be the same as the one we employed
in the prior section: we want to customize the constructor logic for Managers in such a
**|**
-----
way as to provide a job name ... |
In terms of code, we want to redefine an
```
__init__ method in Manager that provides the mgr string for us. |
And like with the
giveRaise customization, we also want to run the original __init__ in Person by calling
```
through the class name, so it still initializes our objects’ state information attributes.
The following extension will do the job—we’ve coded the new Manager constructor and
changed the call that creates tom... |
Although the constructor has a strange name, the effect is identical. |
Because we need Person’s construction logic to run too (to initialize instance attributes), we really have to call it this way;
otherwise, instances would not have any attributes attached.
Calling superclass constructors from redefinitions this way turns out to be a very
common coding pattern in Python. |
By itself, Python uses inheritance to look for and
call only one `__init__ method at construction time—the lowest one in the class tree. |
If`
you need higher __init__ methods to be run at construction time (and you usually do),
**|**
-----
you must call them manually through the superclass’s name. |
The upside to this is that
you can be explicit about which argument to pass up to the superclass’s constructor
and can choose to not call it at all: not calling the superclass constructor allows you to
replace its logic altogether, rather than augmenting it.
The output of this file’s self-test code is the same as befo... |
For example, we wrapped up logic in methods and called back to superclass methods from extensions to
avoid having multiple copies of the same code. |
Most of these steps were a natural
outgrowth of the structuring power of classes.
By and large, that’s all there is to OOP in Python. |
Classes certainly can become larger
than this, and there are some more advanced class concepts, such as decorators and
metaclasses, which we will meet in later chapters. |
In terms of the basics, though, our
classes already do it all. |
In fact, if you’ve grasped the workings of the classes we’ve
written, most OOP Python code should now be within your reach.
###### Other Ways to Combine Classes
Having said that, I should also tell you that although the basic mechanics of OOP are
simple in Python, some of the art in larger programs lies in the way th... |
We’re focusing on inheritance in this tutorial because that’s the mechanism
**|**
-----
the Python language provides, but programmers sometimes combine classes in other
ways, too. |
For example, a common coding pattern involves nesting objects inside each
other to build up composites. |
We’ll explore this pattern in more detail in Chapter 30,
which is really more about design than about Python; as a quick example, though, we
could use this composition idea to code our `Manager extension by` _embedding a_
```
Person, instead of inheriting from it.
```
The following alternative does so by using the `__... |
The giveRaise method here
still achieves customization, by changing the argument passed along to the embedded
object. |
In effect, Manager becomes a controller layer that passes calls down to the embedded object, rather than up to superclass methods:
_# Embedding-based Manager alternative_
```
class Person:
...same...
class Manager:
def __init__(self, name, pay):
self.person = Person(name, 'mgr', pay) # Embed a Pers... |
This pattern works in our example, but it requires about
twice as much code and is less well suited than inheritance to the kinds of direct customizations we meant to express (in fact, no reasonable Python programmer would
code this example this way in practice, except perhaps those writing general tutorials).
```
Mana... |
A controller layer like this alternative Manager, for example, might
come in handy if we want to trace or validate calls to another object’s methods (indeed,
we will use a nearly identical coding pattern when we study class decorators later in the
**|**
-----
book). |
Moreover, a hypothetical Department class like the following could aggregate
other objects in order to treat them as a set. |
Add this to the bottom of the person.py file
to try this on your own:
_# Aggregate embedded objects into a composite_
```
...
bob = Person(...)
sue = Person(...)
tom = Manager(...)
class Department:
def __init__(self, *args):
self.members = list(args)
def addMember(self, person):
self.mem... |
As another example, a
GUI might similarly use inheritance to customize the behavior or appearance of labels
and buttons, but also composition to build up larger packages of embedded widgets,
such as input forms, calculators, and text editors. |
The class structure to use depends
on the objects you are trying to model.
Design issues like composition are explored in Chapter 30, so we’ll postpone further
investigations for now. |
But again, in terms of the basic mechanics of OOP in Python,
our Person and Manager classes already tell the entire story. |
Having mastered the basics
of OOP, though, developing general tools for applying it more easily in your scripts is
often a natural next step—and the topic of the next section.
###### Catching Built-in Attributes in 3.0
In Python 3.0 (and 2.6 if new-style classes are used), the alternative delegation-based
```
Manager... |
Although we know
that __str__ is the only such name used in our specific example, this a general issue for
delegation-based classes.
Recall that built-in operations like printing and indexing implicitly invoke operator
overloading methods such as __str__ and __getitem__. |
In 3.0, built-in operations like
**|**
-----
###### Step 6: Using Introspection Tools
Let’s make one final tweak before we throw our objects onto a database. |
As they are,
our classes are complete and demonstrate most of the basics of OOP in Python. |
They
still have two remaining issues we probably should iron out, though, before we go live
with them:
- First, if you look at the display of the objects as they are right now, you’ll notice
that when you print tom the Manager labels him as a Person. |
That’s not technically
incorrect, since `Manager is a kind of customized and specialized` `Person. |
Still, it`
would be more accurate to display objects with the most specific (that is, lowest)
classes possible.
- Second, and perhaps more importantly, the current display format shows only the
attributes we include in our __str__, and that might not account for future goals.
For example, we can’t yet verify that tom... |
Worse, if we ever expand or otherwise change the set of attributes assigned to our objects in __init__, we’ll have to remember to also update __str__
for new names to be displayed, or it will become out of sync over time.
The last point means that, yet again, we’ve made potential extra work for ourselves in
the future... |
Because any disparity in __str__ will
be reflected in the program’s output, this redundancy may be more obvious than the
other forms we addressed earlier; still, avoiding extra work in the future is generally a
_good thing._
**|**
-----
###### Special Class Attributes
We can address both issues with Python’s intro... |
These
tools are somewhat advanced and generally used more by people writing tools for other
programmers to use than by programmers developing applications. |
Even so, a basic
knowledge of some of these tools is useful because they allow us to write code that
processes classes in generic ways. |
In our code, for example, there are two hooks that
can help us out, both of which were introduced near the end of the preceding chapter:
- The built-in instance.__class__ attribute provides a link from an instance to the
class from which it was created. |
Classes in turn have a __name__, just like modules,
and a __bases__ sequence that provides access to superclasses. |
We can use these
here to print the name of the class from which an instance is made rather than one
we’ve hardcoded.
- The built-in object.__dict__ attribute provides a dictionary with one key/value
pair for every attribute attached to a namespace object (including modules, classes,
and instances). |
Because it is a dictionary, we can fetch its keys list, index by key,
iterate over its keys, and so on, to process all attributes generically. |
We can use this
here to print every attribute in any instance, not just those we hardcode in custom
displays.
Here’s what these tools look like in action at Python’s interactive prompt. |
Notice how
we load Person at the interactive prompt with a from statement here—class names live
in and are imported from modules, exactly like function names and other variables:
```
>>> from person import Person
>>> bob = Person('Bob Smith')
```
`>>> print(bob)` _# Show bob's __str___
```
[Person: Bob Smith, 0]... |
Since
slots really belong to classes instead of instances, and since they are very rarely used in
any event, we can safely ignore them here and focus on the normal __dict__.
###### A Generic Display Tool
We can put these interfaces to work in a superclass that displays accurate class names
and formats all attributes ... |
Open a new file in your text editor
to code the following—it’s a new, independent module named classtools.py that implements just such a class. |
Because its __str__ print overload uses generic introspection
tools, it will work on any instance, regardless of its attributes set. |
And because this is a
class, it automatically becomes a general formatting tool: thanks to inheritance, it can
be mixed into any class that wishes to use its display format. |
As an added bonus, if we
ever want to change how instances are displayed we need only change this class, as
every class that inherits its __str__ will automatically pick up the new format when it’s
next run:
_# File classtools.py (new)_
```
"Assorted class utilities and tools"
class AttrDisplay:
"""
Provid... |
Can be mixed into any class,
and will work on any instance.
"""
def gatherAttrs(self):
attrs = []
for key in sorted(self.__dict__):
attrs.append('%s=%s' % (key, getattr(self, key)))
return ', '.join(attrs)
def __str__(self):
return '[%s: %s]' % (self.__class__.__name__, s... |
As we saw in Chapter 15, docstrings can be
placed at the top of simple functions and modules, and also at the start of classes and
their methods; the help function and the PyDoc tool extracts and displays these automatically (we’ll look at docstrings again in Chapter 28).
When run directly, this module’s self-test mak... |
As an intended consequence, we
don’t see attributes inherited by the instance from classes above it in the tree (e.g.,
```
count in this file’s self-test code). |
Inherited class attributes are attached to the class only,
```
not copied down to instances.
If you ever do wish to include inherited attributes too, you can climb the __class__ link
to the instance’s class, use the __dict__ there to fetch class attributes, and then iterate
through the class’s __bases__ attribute to ... |
If you’re a fan of simple code, running a built-in dir call on the instance
instead of using __dict__ and climbing would have much the same effect, since dir
results include inherited names in the sorted results list:
```
>>> from person import Person
>>> bob = Person('Bob Smith')
```
_# In Python 2.6:_
`>>> bob.... |
Technically, dir
returns more in 3.0 because classes are all “new style” and inherit a large set of operator
overloading names from the class type. |
In fact, you’ll probably want to filter out most
of the __X__ names in the 3.0 dir result, since they are internal implementation details
and not something you’d normally want to display.
In the interest of space, we’ll leave optional display of inherited class attributes with
either tree climbs or dir as suggested ex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.