Text stringlengths 1 9.41k |
|---|
self is the name commonly given to the first (leftmost) argument in a class method
function; Python automatically fills it in with the instance object that is the implied
subject of the method call. |
This argument need not be called self (though this is
a very strong convention); its position is what is significant. |
(Ex-C++ or Java programmers might prefer to call it this because in those languages that name reflects
the same idea; in Python, though, this argument must always be explicit.)
6. |
Operator overloading is coded in a Python class with specially named methods;
they all begin and end with double underscores to make them unique. |
These are
not built-in or reserved names; Python just runs them automatically when an instance appears in the corresponding operation. |
Python itself defines the mappings
from operations to special method names.
7. |
Operator overloading is useful to implement objects that resemble built-in types
(e.g., sequences or numeric objects such as matrixes), and to mimic the built-in
type interface expected by a piece of code. |
Mimicking built-in type interfaces enables you to pass in class instances that also have state information—i.e., attributes
that remember data between operation calls. |
You shouldn’t use operator overloading when a simple named method will suffice, though.
8. |
The __init__ constructor method is the most commonly used; almost every class
uses this method to set initial values for instance attributes and perform other
startup tasks.
9. |
The special `self argument in method functions and the` `__init__ constructor`
method are the two cornerstones of OOP code in Python.
**|**
-----
###### CHAPTER 27
### A More Realistic Example
We’ll dig into more class syntax details in the next chapter. |
Before we do, though, I’d
like to show you a more realistic example of classes in action that’s more practical than
what we’ve seen so far. |
In this chapter, we’re going to build a set of classes that do
something more concrete—recording and processing information about people. |
As
you’ll see, what we call instances and classes in Python programming can often serve
the same roles as records and programs in more traditional terms.
Specifically, in this chapter we’re going to code two classes:
- Person—a class that creates and processes information about people
- Manager—a customization of ... |
That way, you
can use this code as a template for fleshing out a full-blown personal database written
entirely in Python.
Besides actual utility, though, our aim here is also educational: this chapter provides a
tutorial on object-oriented programming in Python. |
Often, people grasp the last chapter’s class syntax on paper, but have trouble seeing how to get started when confronted
with having to code a new class from scratch. |
Toward this end, we’ll take it one step
at a time here, to help you learn the basics; we’ll build up the classes gradually, so you
can see how their features come together in complete programs.
In the end, our classes will still be relatively small in terms of code, but they will demonstrate all of the main ideas in P... |
Despite its syntax details, Python’s class system really is largely just a matter of searching for an attribute in a tree
of objects, along with a special first argument for functions.
-----
###### Step 1: Making Instances
OK, so much for the design phase—let’s move on to implementation. |
Our first task is
to start coding the main class, Person. In your favorite text editor, open a new file for
the code we’ll be writing. |
It’s a fairly strong convention in Python to begin module
names with a lowercase letter and class names with an uppercase letter; like the name
of self arguments in methods, this is not required by the language, but it’s so common
that deviating might be confusing to people who later read your code. |
To conform,
we’ll call our new module file person.py and our class within it Person, like this:
_# File person.py (start)_
```
class Person:
```
All our work will be done in this file until later in this chapter. |
We can code any number
of functions and classes in a single module file in Python, and this one’s person.py name
might not make much sense if we add unrelated components to it later. |
For now, we’ll
assume everything in it will be Person-related. |
It probably should be anyhow—as we’ve
learned, modules tend to work best when they have a single, cohesive purpose.
###### Coding Constructors
Now, the first thing we want to do with our Person class is record basic information
about people—to fill out record fields, if you will. |
Of course, these are known as instance object attributes in Python-speak, and they generally are created by assignment
to self attributes in class method functions. |
The normal way to give instance attributes
their first values is to assign them to self in the __init__ _constructor method, which_
contains code run automatically by Python each time an instance is created. |
Let’s add
one to our class:
_# Add record field initialization_
```
class Person:
```
`def __init__(self, name, job, pay):` _# Constructor takes 3 arguments_
`self.name = name` _# Fill out fields when created_
`self.job = job` _# self is the new instance object_
```
self.pay = pay
```
This is a very common c... |
In OO terms, self is the newly created instance object, and name, job, and
```
pay become state information—descriptive data saved on an object for later use. |
Al
```
though other techniques (such as enclosing scope references) can save details, too,
instance attributes make this very explicit and easy to understand.
Notice that the argument names appear twice here. |
This code might seem a bit redundant at first, but it’s not. |
The job argument, for example, is a local variable in the scope
of the __init__ function, but self.job is an attribute of the instance that’s the implied
**|**
-----
subject of the method call. |
They are two different variables, which happen to have the
same name. By assigning the job local to the self.job attribute with self.job=job, we
save the passed-in job on the instance for later use. |
As usual in Python, where a name
is assigned (or what object it is assigned to) determines what it means.
Speaking of arguments, there’s really nothing magical about __init__, apart from the
fact that it’s called automatically when an instance is made and has a special first argument. |
Despite its weird name, it’s a normal function and supports all the features of
functions we’ve already covered. |
We can, for example, provide defaults for some of its
arguments, so they need not be provided in cases where their values aren’t available or
useful.
To demonstrate, let’s make the job argument optional—it will default to None, meaning
the person being created is not (currently) employed. |
If `job defaults to` `None, we’ll`
probably want to default pay to 0, too, for consistency (unless some of the people you
know manage to get paid without having jobs!). |
In fact, we have to specify a default
for pay because according to Python’s syntax rules, any arguments in a function’s header
after the first default must all have defaults, too:
_# Add defaults for constructor arguments_
```
class Person:
```
`def __init__(self, name, job=None, pay=0):` _# Normal function args_
`... |
The self argu
```
ment, as usual, is filled in by Python automatically to refer to the instance object—
assigning values to attributes of self attaches them to the new instance.
###### Testing As You Go
This class doesn’t do much yet—it essentially just fills out the fields of a new record—
but it’s a real working cl... |
At this point we could add more code to it for more features,
but we won’t do that yet. |
As you’ve probably begun to appreciate already, programming
in Python is really a matter of incremental prototyping—you write some code, test it,
write more code, test again, and so on. |
Because Python provides both an interactive
session and nearly immediate turnaround after code changes, it’s more natural to test
as you go than to write a huge amount of code to test all at once.
Before adding more features, then, let’s test what we’ve got so far by making a few
instances of our class and displaying ... |
We
could do this interactively, but as you’ve also probably surmised by now, interactive
testing has its limits—it gets tedious to have to reimport modules and retype test cases
each time you start a new testing session. |
More commonly, Python programmers use
**|**
-----
the interactive prompt for simple one-off tests but do more substantial testing by writing
code at the bottom of the file that contains the objects to be tested, like this:
_# Add incremental self-test code_
```
class Person:
def __init__(self, name, job=None... |
Also note how we use keyword arguments when making sue; we could
pass by position instead, but the keywords may help remind us later what the data is
(and they allow us to pass the arguments in any left-to-right order we like). |
Again,
despite its unusual name, __init__ is a normal function, supporting everything you
already know about functions—including both defaults and pass-by-name keyword
arguments.
When this file runs as a script, the test code at the bottom makes two instances of our
class and prints two attributes of each (name and pa... |
Each is an independent
record of information. |
Technically, bob and sue are both namespace objects—like all
class instances, they each have their own independent copy of the state information
created by the class. |
Because each instance of a class has its own set of self attributes,
classes are a natural for recording information for multiple objects this way; just like
built-in types, classes serve as a sort of object factory. |
Other Python program structures,
such as functions and modules, have no such concept.
###### Using Code Two Ways
As is, the test code at the bottom of the file works, but there’s a big catch—its top-level
```
print statements run both when the file is run as a script and when it is imported as a
```
module. |
This means if we ever decide to import the class in this file in order to use it
somewhere else (and we will later in this chapter), we’ll see the output of its test code
**|**
-----
every time the file is imported. |
That’s not very good software citizenship, though: client
programs probably don’t care about our internal tests and won’t want to see our output
mixed in with their own.
Although we could split the test code off into a separate file, it’s often more convenient
to code tests in the same file as the items to be tested. |
It would be better to arrange to
run the test statements at the bottom only when the file is run for testing, not when the
file is imported. |
That’s exactly what the module __name__ check is designed for, as you
learned in the preceding part of this book. |
Here’s what this addition looks like:
_# Allow this file to be imported as well as run/tested_
```
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
```
`if __name__ == '__main__':` _# When run for testing only_
_# self-test code_
```
b... |
When run directly,
this file creates two instances of our class as before, and prints two attributes of each;
again, because each instance is an independent namespace object, the values of their
attributes differ.
###### Version Portability Note
I’m running all the code in this chapter under Python 3.0, and using the... |
If you run under 2.6 the code will work as-is, but you’ll notice
parentheses around some output lines because the extra parentheses in `prints turn`
multiple items into a tuple:
```
c:\misc> c:\python26\python person.py
('Bob Smith', 0)
('Sue Jones', 100000)
```
**|**
-----
###### Step 2: Adding Behavio... |
Although
classes add an extra layer of structure, they ultimately do most of their work by embedding and processing basic core data types like lists and strings. |
In other words, if
you already know how to use Python’s simple core types, you already know much of
the Python class story; classes are really just a minor structural extension.
For example, the name field of our objects is a simple string, so we can extract last names
from our objects by splitting on spaces and index... |
These are all core data type operations, which work whether their subjects are embedded in class instances or not:
`>>> name = 'Bob Smith'` _# Simple string, outside class_
`>>> name.split()` _# Extract last name_
```
['Bob', 'Smith']
```
`>>> name.split()[-1]` _# Or [1], if always just two parts_
```
'Smith'
``... |
This task also involves basic operations that work on Python’s core objects, regardless of whether they are standalone or
embedded in a class structure:
`>>> pay = 100000` _# Simple variable, outside class_
`>>> pay *= 1.10` _# Give a 10% raise_
`>>> print(pay)` _# Or: pay = pay * 1.10, if you like to type_
```
1100... |
The operations are the same,
```
but the subject objects are attached to attributes in our class structure:
_# Process embedded built-in types: strings, mutability_
```
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
if __name__ == '__m... |
In a sense, `sue is also a` _mutable_
object—her state changes in-place just like a list after an append call:
```
Bob Smith 0
Sue Jones 100000
Smith
110000.0
```
The preceding code works as planned, but if you show it to a veteran software developer
he’ll probably tell you that its general approach is not a g... |
Hardcoding operations like these outside of the class can lead to maintenance problems in
the future.
For example, what if you’ve hardcoded the last-name-extraction formula at many different places in your program? |
If you ever need to change the way it works (to support
a new name structure, for instance), you’ll need to hunt down and update every occurrence. |
Similarly, if the pay-raise code ever changes (e.g., to require approval or
database updates), you may have multiple copies to modify. |
Just finding all the appearances of such code may be problematic in larger programs—they may be scattered
across many files, split into individual steps, and so on.
###### Coding Methods
What we really want to do here is employ a software design concept known as encap_sulation. |
The idea with encapsulation is to wrap up operation logic behind interfaces,_
such that each operation is coded only once in our program. |
That way, if our needs
change in the future, there is just one copy to update. |
Moreover, we’re free to change
the single copy’s internals almost arbitrarily, without breaking the code that uses it.
In Python terms, we want to code operations on objects in class methods, instead of
littering them throughout our program. |
In fact, this is one of the things that classes are
very good at—factoring code to remove redundancy and thus optimize maintainability.
As an added bonus, turning operations into methods enables them to be applied to any
instance of the class, not just those that they’ve been hardcoded to process.
This is all simpler ... |
The following achieves encapsulation by moving the two operations from code outside the class into class methods.
While we’re at it, let’s change our self-test code at the bottom to use the new methods
we’re creating, instead of hardcoding operations:
**|**
-----
_# Add methods to encapsulate operations for maintai... |
The instance is the subject of the method
call and is passed to the method’s self argument automatically.
The transformation to the methods in this version is straightforward. |
The new
```
lastName method, for example, simply does to self what the previous version hardco
```
ded for bob, because self is the implied subject when the method is called. |
lastName
also returns the result, because this operation is a called function now; it computes a
value for its caller to use, even if it is just to be printed. |
Similarly, the new giveRaise
method just does to self what we did to sue before.
When run now, our file’s output is similar to before—we’ve mostly just refactored the
code to allow for easier changes in the future, not altered its behavior:
```
Bob Smith 0
Sue Jones 100000
Smith Jones
110000
```
A few coding ... |
First, notice that sue’s pay is now still
an integer after a pay raise—we convert the math result back to an integer by calling
the int built-in within the method. |
Changing the value to either int or float is probably
not a significant concern for most purposes (integer and floating-point objects have the
same interfaces and can be mixed within expressions), but we may need to address
rounding issues in a real system (money probably matters to Persons!).
As we learned in Chapter... |
For this example, we’ll simply truncate any cents with
**|**
-----
```
int. |
(For another idea, also see the money function in the formats.py module of Chap
```
ter 24; you can import this tool to show pay with commas, cents, and dollar signs.)
Second, notice that we’re also printing sue’s last name this time—because the last-name
logic has been encapsulated in a method, we get to use it on an... |
Specifically:
- In the first call, bob.lastName(), bob is the implied subject passed to self.
- In the second call, sue.lastName(), sue goes to self instead.
Trace through these calls to see how the instance winds up in self. |
The net effect is
that the method fetches the name of the implied subject each time. The same happens
for giveRaise. |
We could, for example, give bob a raise by calling giveRaise for both
instances this way, too; but unfortunately, bob’s zero pay will prevent him from getting
a raise as the program is currently coded (something we may want to address in a future
2.0 release of our software).
Finally, notice that the giveRaise method ... |
That may be too radical an assumption in the real
world (a 1000% raise would probably be a bug for most of us!); we’ll let it pass for this
prototype, but we might want to test or at least document this in a future iteration of
this code. |
Stay tuned for a rehash of this idea in a later chapter in this book, where we’ll
code something called function decorators and explore Python’s assert statement—
alternatives that can do the validity test for us automatically during development.
###### Step 3: Operator Overloading
At this point, we have a fairly ful... |
It would be nice if displaying an instance all at once actually gave us some
```
useful information. |
Unfortunately, the default display format for an instance object
isn’t very good—it displays the object’s class name, and its address in memory (which
is essentially useless in Python, except as a unique identifier).
To see this, change the last line in the script to print(sue) so it displays the object as a
whole. |
Here’s what you’ll get (the output says that sue is an “object” in 3.0 and an
“instance” in 2.6):
```
Bob Smith 0
Sue Jones 100000
Smith Jones
<__main__.Person object at 0x02614430>
```
**|**
-----
###### Providing Print Displays
Fortunately, it’s easy to do better by employing operator overloading—coding ... |
Specifically, we can make use of what is probably the second most commonly
used operator overloading method in Python, after __init__: the __str__ method introduced in the preceding chapter. |
__str__ is run automatically every time an instance
is converted to its print string. |
Because that’s what printing an object does, the net
transitive effect is that printing an object displays whatever is returned by the object’s
```
__str__ method, if it either defines one itself or inherits one from a superclass (double
```
underscored names are inherited just like any other).
Technically speaking, t... |
Constructors are so common, though, that they almost seem like a special
case. |
More focused methods like __str__ allow us to tap into specific operations and
provide specialized behavior when our objects are used in those contexts.
Let’s put this into code. |
The following extends our class to give a custom display that
lists attributes when our class’s instances are displayed as a whole, instead of relying
on the less useful default display:
_# Add __str__ overload method for printing objects_
```
class Person:
def __init__(self, name, job=None, pay=0):
self.n... |
Again, everything you’ve already learned about both built-in types and
functions applies to class-based code. |
Classes largely just add an additional layer of
_structure that packages functions and data together and supports extensions._
**|**
-----
We’ve also changed our self-test code to print objects directly, instead of printing individual attributes. |
When run, the output is more coherent and meaningful now; the
“[...]” lines are returned by our new __str__, run automatically by print operations:
```
[Person: Bob Smith, 0]
[Person: Sue Jones, 100000]
Smith Jones
[Person: Sue Jones, 110000]
```
Here’s a subtle point: as we’ll learn in the next chapter, a rel... |
Sometimes
```
classes provide both a __str__ for user-friendly displays and a __repr__ with extra details for developers to view. |
Because printing runs __str__ and the interactive prompt
echoes results with __repr__, this can provide both target audiences with an appropriate
display. |
Since we’re not interested in displaying an as-code format, __str__ is sufficient
for our class.
###### Step 4: Customizing Behavior by Subclassing
At this point, our class captures much of the OOP machinery in Python: it makes
instances, provides behavior in methods, and even does a bit of operator overloading
now t... |
It effectively packages our data and logic
together into a single, self-contained software component, making it easy to locate code
and straightforward to change it in the future. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.