Text stringlengths 1 9.41k |
|---|
Here is my solution (file myclient.py):
```
from mymod import countLines, countChars
print(countLines('mymod.py'), countChars('mymod.py'))
% python myclient.py
13 346
```
As for the rest of this one, mymod’s functions are accessible (that is, importable) from
the top level of myclient, since from simpl... |
For example, another
file can say this:
```
import myclient
myclient.countLines(...)
from myclient import countChars
countChars(...)
```
If `myclient used` `import instead of` `from, you’d need to use a path to get to the`
functions in mymod through myclient:
```
import myclient
myclient.mymod.... |
Using the following
code, you wind up with three different copies of the name somename (mod1.somename,
```
collector.somename, and __main__.somename); all three share the same integer ob
```
ject initially, and only the name somename exists at the interactive prompt as is:
_# File mod1.py_
```
somename = 42
```
... |
Package imports. For this, I put the mymod.py solution file listed for exercise 3 into
a directory package. |
The following is what I did to set up the directory and its
required __init__.py file in a Windows console interface; you’ll need to interpolate
for other platforms (e.g., use mv and vi instead of move and edit). |
This works in any
**|**
-----
directory (I just happened to run my commands in Python’s install directory), and
you can do some of this from a file explorer GUI, too.
When I was done, I had a _mypkg subdirectory that contained the files_
___init__.py and mymod.py. |
You need an __init__.py in the mypkg directory, but_
not in its parent; mypkg is located in the home directory component of the module
search path. |
Notice how a print statement coded in the directory’s initialization
file fires only the first time it is imported, not the second:
```
C:\python30> mkdir mypkg
C:\Python30> move mymod.py mypkg\mymod.py
C:\Python30> edit mypkg\__init__.py
...coded a print statement...
C:\Python30> python
>... |
Reloads. This exercise just asks you to experiment with changing the changer.py
example in the book, so there’s nothing to show here.
7. Circular imports. |
The short story is that importing recur2 first works because the
recursive import then happens at the import in recur1, not at a from in recur2.
The long story goes like this: importing recur2 first works because the recursive
import from recur1 to recur2 fetches recur2 as a whole, instead of getting specific
names. |
recur2 is incomplete when it’s imported from recur1, but because it uses
```
import instead of from, you’re safe: Python finds and returns the already created
recur2 module object and continues to run the rest of recur1 without a glitch.
```
When the recur2 import resumes, the second from finds the name Y in recur... |
Running a file as a script is not the
same as importing it as a module; these cases are the same as running the first
```
import or from in the script interactively. |
For instance, running recur1 as a script
```
is the same as importing recur2 interactively, as recur2 is the first module imported
in recur1.
###### Part VI, Classes and OOP
See “Test Your Knowledge: Part VI Exercises” on page 816 in Chapter 31 for the
exercises.
1. |
Inheritance. Here’s the solution code for this exercise (file adder.py), along with
some interactive tests. |
The __add__ overload has to appear only once, in the superclass, as it invokes type-specific add methods in subclasses:
```
class Adder:
def add(self, x, y):
```
**|** **f**
-----
```
print('not implemented!')
def __init__(self, start=[]):
self.data = start
def __add__(self, other): ... |
And, once you’ve gotten to this point, you’ll probably find that you can get rid of `add altogether and simply define type-specific`
```
__add__ methods in the two subclasses.
```
2. |
Operator overloading. The solution code (file mylist.py) uses a few operator overloading methods that the text didn’t say much about, but they should be straightforward to understand. |
Copying the initial value in the constructor is important
because it may be mutable; you don’t want to change or have a reference to an
object that’s possibly shared somewhere outside the class. |
The __getattr__ method
routes calls to the wrapped list. |
For hints on an easier way to code this in Python
2.2 and later, see “Extending Types by Subclassing” on page 775 in Chapter 31:
```
class MyList:
def __init__(self, start):
#self.wrapped = start[:] # Copy start: no side effects
self.wrapped = [] # Make sure it's a list here
f... |
You would be able to copy a MyList start value by slicing because its
class overloads the slicing operation and provides the expected list interface; however, you need to avoid slice-based copying for objects such as strings. |
Also, note
that sets are a built-in type in Python today, so this is largely just a coding exercise
(see Chapter 5 for more on sets).
3. Subclassing. My solution (mysub.py) appears below. |
Your solution should be
similar:
```
from mylist import MyList
class MyListSub(MyList):
calls = 0 # Shared by instances
def __init__(self, start):
self.adds = 0 # Varies in each instance
MyList.__init__(self, start)
def __add__(self, other):
... |
Metaclass methods. I worked through this exercise as follows. Notice that in Python
2.6, operators try to fetch attributes through __getattr__, too; you need to return
a value to make them work. |
Caveat: as noted in Chapter 30, __getattr__ is not
called for built-in operations in Python 3.0, so the following expression won’t work
as shown; in 3.0, a class like this must redefine __X__ operator overloading methods
explicitly. |
More on this in Chapters 30, 37, and 38.
```
>>> class Meta:
... def __getattr__(self, name):
... print('get', name)
... def __setattr__(self, name, value):
... |
print('set', name, value)
...
>>> x = Meta()
>>> x.append
get append
>>> x.spam = "pork"
set spam pork
>>>
>>> x + 2
get __coerce__
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: call of non-function
>>>
>>> x[1]
get __getitem__
Trace... |
Set objects. Here’s the sort of interaction you should get. |
Comments explain which
methods are called:
```
% python
>>> from setwrapper import Set
```
`>>> x = Set([1, 2, 3, 4])` _# Runs __init___
```
>>> y = Set([3, 4, 5])
```
`>>> x & y` _# __and__, intersect, then __repr___
```
Set:[3, 4]
```
`>>> x | y` _# __or__, union, then __repr___
**|** **f**
----... |
It only needs to replace two methods in the original set. |
The
class’s documentation string explains how it works:
```
from setwrapper import Set
class MultiSet(Set):
"""
Inherits all Set names, but extends intersect
and union to support multiple operands; note
that "self" is still the first argument (stored
in the *args argument now); also note that th... |
Note
that you can intersect by using `& or calling` `intersect, but you must call`
```
intersect for three or more operands; & is a binary (two-sided) operator. |
Also, note
```
that we could have called MultiSet simply Set to make this change more transparent if we used setwrapper.Set to refer to the original within multiset:
**|**
-----
```
>>> from multiset import *
>>> x = MultiSet([1,2,3,4])
>>> y = MultiSet([3,4,5])
>>> z = MultiSet([0,1,2])
```
`>>> ... |
Class tree links. Here is the way I changed the lister classes, and a rerun of the test
to show its format. |
Do the same for the dir-based version, and also do this when
formatting class objects in the tree climber variant:
```
class ListInstance:
def __str__(self):
return '<Instance of %s(%s), address %s:\n%s>' % (
self.__class__.__name__, # My class's name
self.__supers... |
Composition. My solution is below (file lunch.py), with comments from the description mixed in with the code. |
This is one case where it’s probably easier to
express a problem in Python than it is in English:
```
class Lunch:
def __init__(self): # Make/embed Customer, Employee
self.cust = Customer()
self.empl = Employee()
def order(self, foodName): # Start Customer order simu... |
Zoo animal hierarchy. Here is the way I coded the taxonomy in Python (file
_zoo.py); it’s artificial, but the general coding pattern applies to many real structures,_
from GUIs to employee databases. |
Notice that the self.speak reference in Animal
triggers an independent inheritance search, which finds speak in a subclass. Test
this interactively per the exercise description. |
Try extending this hierarchy with
new classes, and making instances of various classes in the tree:
```
class Animal:
def reply(self): self.speak() # Back to subclass
def speak(self): print('spam') # Custom message
class Mammal(Animal):
def speak(self): print('huh?')
class C... |
The Dead Parrot Sketch. Here’s how I implemented this one (file parrot.py). |
Notice
how the line method in the Actor superclass works: by accessing self attributes
twice, it sends Python back to the instance twice, and hence invokes two inheritance
searches—self.name and self.says() find information in the specific subclasses:
```
class Actor:
def line(self): print(self.name + ':', ... |
try/except. My version of the `oops function (file` _oops.py) follows. |
As for the_
noncoding questions, changing oops to raise a KeyError instead of an IndexError
means that the try handler won’t catch the exception (it “percolates” to the top
level and triggers Python’s default error message). |
The names KeyError and Index
```
Error come from the outermost built-in names scope. |
Import builtins
```
(__builtin__ in Python 2.6) and pass it as an argument to the dir function to see
for yourself:
```
def oops():
raise IndexError()
def doomed():
try:
oops()
except IndexError:
```
**|** **f**
-----
```
print('caught an index error!')
else:
... |
Exception objects and lists. |
Here’s the way I extended this module for an exception
of my own:
```
class MyError(Exception): pass
def oops():
raise MyError('Spam!')
def doomed():
try:
oops()
except IndexError:
print('caught an index error!')
except MyError as data:
print('caught error:', ... |
The instance must be
inheriting both an __init__ and a __repr__ or __str__ from Python’s Exception
class, or it would print like the class does. |
See Chapter 34 for details on how this
works in built-in exception classes.
3. Error handling. Here’s one way to solve this one (file safe2.py). |
I did my tests in a
file, rather than interactively, but the results are about the same.
```
import sys, traceback
def safe(entry, *args):
try:
entry(*args) # Catch everything else
except:
traceback.print_exc()
print('Got', sys.exc_info()[0], sys.exc_info()[1])
... |
Here are a few examples for you to study as time allows; for more, see follow-up
books and the Web:
_# Find the largest Python source file in a single directory_
```
import os, glob
dirname = r'C:\Python30\Lib'
allsizes = []
allpy = glob.glob(dirname + os.sep + '*.py')
for filename in allpy:
... |
# Python Tutorial
**CHAPTER**
### ONE
WHETTING YOUR APPETITE
If you do much work on computers, eventually you find that there’s some task you’d like to automate. |
For
example, you may wish to perform a search-and-replace over a large number of text files, or rename and
rearrange a bunch of photo files in a complicated way. |
Perhaps you’d like to write a small custom database,
or a specialized GUI application, or a simple game.
If you’re a professional software developer, you may have to work with several C/C++/Java libraries but
find the usual write/compile/test/re-compile cycle is too slow. |
Perhaps you’re writing a test suite for such
a library and find writing the testing code a tedious task. |
Or maybe you’ve written a program that could
use an extension language, and you don’t want to design and implement a whole new language for your
application.
Python is just the language for you.
You could write a Unix shell script or Windows batch files for some of these tasks, but shell scripts are best
at moving ar... |
You could
write a C/C++/Java program, but it can take a lot of development time to get even a first-draft program.
Python is simpler to use, available on Windows, Mac OS X, and Unix operating systems, and will help you
get the job done more quickly.
Python is simple to use, but it is a real programming language, offer... |
On the other hand, Python also offers much
more error checking than C, and, being a very-high-level language, it has high-level data types built in, such
as flexible arrays and dictionaries. |
Because of its more general data types Python is applicable to a much
larger problem domain than Awk or even Perl, yet many things are at least as easy in Python as in those
languages.
Python allows you to split your program into modules that can be reused in other Python programs. |
It
comes with a large collection of standard modules that you can use as the basis of your programs — or as
examples to start learning to program in Python. |
Some of these modules provide things like file I/O, system
calls, sockets, and even interfaces to graphical user interface toolkits like Tk.
Python is an interpreted language, which can save you considerable time during program development
because no compilation and linking is necessary. |
The interpreter can be used interactively, which makes it
easy to experiment with features of the language, to write throw-away programs, or to test functions during
bottom-up program development. |
It is also a handy desk calculator.
Python enables programs to be written compactly and readably. |
Programs written in Python are typically
much shorter than equivalent C, C++, or Java programs, for several reasons:
- the high-level data types allow you to express complex operations in a single statement;
- statement grouping is done by indentation instead of beginning and ending brackets;
- no variable or ... |
Once you
-----
are really hooked, you can link the Python interpreter into an application written in C and use it as an
extension or command language for that application.
By the way, the language is named after the BBC show “Monty Python’s Flying Circus” and has nothing
to do with reptiles. |
Making references to Monty Python skits in documentation is not only allowed, it is
encouraged!
Now that you are all excited about Python, you’ll want to examine it in some more detail. |
Since the best
way to learn a language is to use it, the tutorial invites you to play with the Python interpreter as you read.
In the next chapter, the mechanics of using the interpreter are explained. |
This is rather mundane information,
but essential for trying out the examples shown later.
The rest of the tutorial introduces various features of the Python language and system through examples,
beginning with simple expressions, statements and data types, through functions and modules, and finally
touching upon adva... |
(E.g., /usr/local/python
is a popular alternative location.)
On Windows machines, the Python installation is usually placed in `C:\Program Files\Python37\,` though
you can change this when you’re running the installer. |
To add this directory to your path, you can
type the following command into the command prompt in a DOS box:
```
set path=%path%;C:\Program Files\Python37\
```
Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes
the interpreter to exit with a zero exit status. |
If that doesn’t work, you can exit the interpreter by typing
the following command: quit().
The interpreter’s line-editing features include interactive editing, history substitution and code completion
on systems that support readline. |
Perhaps the quickest check to see whether command line editing is
supported is typing Control-P to the first Python prompt you get. |
If it beeps, you have command line
editing; see Appendix Interactive Input Editing and History Substitution for an introduction to the keys. |
If
nothing appears to happen, or if ^P is echoed, command line editing isn’t available; you’ll only be able to
use backspace to remove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty
device, it reads and executes commands inter... |
Since Python statements often contain spaces or other
characters that are special to the shell, it is usually advised to quote command in its entirety with single
quotes.
Some Python modules are also useful as scripts. |
These can be invoked using python -m module [arg] ...,
which executes the source file for module as if you had spelled out its full name on the command line.
When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode
afterwards. |
This can be done by passing -i before the script.
1 On Unix, the Python 3.x interpreter is by default not installed with the executable named python, so that it does not
conflict with a simultaneously installed Python 2.x executable.
-----
All command line options are described in using-on-general.
#### 2.1.1 Argu... |
You can access this list by executing import
```
sys. The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an
```
empty string. |
When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'.
When -c command is used, sys.argv[0] is set to '-c'. |
When -m module is used, sys.argv[0] is set to
the full name of the located module. |
Options found after -c command or -m module are not consumed by
the Python interpreter’s option processing but left in sys.argv for the command or module to handle.
#### 2.1.2 Interactive Mode
When commands are read from a tty, the interpreter is said to be in interactive mode. |
In this mode it prompts
for the next command with the primary prompt, usually three greater-than signs (>>>); for continuation lines
it prompts with the secondary prompt, by default three dots (...). |
The interpreter prints a welcome message
stating its version number and a copyright notice before printing the first prompt:
```
$ python3.7
Python 3.7 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
Continuation lines are needed when... |
As an example, take a look at this if
statement:
```
>>> the_world_is_flat = True
>>> if the_world_is_flat:
... |
print("Be careful not to fall off!")
...
Be careful not to fall off!
```
For more on interactive mode, see Interactive Mode.
### 2.2 The Interpreter and Its Environment
#### 2.2.1 Source Code Encoding
By default, Python source files are treated as encoded in UTF-8. |
In that encoding, characters of most
languages in the world can be used simultaneously in string literals, identifiers and comments — although
the standard library only uses ASCII characters for identifiers, a convention that any portable code should
follow. |
To display all these characters properly, your editor must recognize that the file is UTF-8, and it
must use a font that supports all the characters in the file.
To declare an encoding other than the default one, a special comment line should be added as the first line
of the file. |
The syntax is as follows:
```
# -*- coding: encoding -*
```
where encoding is one of the valid codecs supported by Python.
-----
For example, to declare that Windows-1252 encoding is to be used, the first line of your source code file
should be:
```
# -*- coding: cp1252 -*
```
One exception to the first line rule is... |
In this case,
the encoding declaration should be added as the second line of the file. |
For example:
-----
-----
**CHAPTER**
### THREE
AN INFORMAL INTRODUCTION TO PYTHON
In the following examples, input and output are distinguished by the presence or absence of prompts (>>>
and …): to repeat the example, you must type everything after the prompt, when the prompt appears; lines
that do not begin wi... |
Note that a secondary prompt on a line
by itself in an example means you must type a blank line; this is used to end a multi-line command.
Many of the examples in this manual, even those entered at the interactive prompt, include comments.
Comments in Python start with the hash character, #, and extend to the end of t... |
A
comment may appear at the start of a line or following whitespace or code, but not within a string literal.
A hash character within a string literal is just a hash character. |
Since comments are to clarify code and are
not interpreted by Python, they may be omitted when typing in examples.
Some examples:
```
# this is the first comment
spam = 1 # and this is the second comment
# ... |
and now a third!
text = "# This is not a comment because it's inside quotes."
### 3.1 Using Python as a Calculator
```
Let’s try some simple Python commands. |
Start the interpreter and wait for the primary prompt, >>>. |
(It
shouldn’t take long.)
#### 3.1.1 Numbers
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value.
Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for
example, Pascal or C); parentheses (()) can be used for ... |
For example:
```
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
```
The integer numbers (e.g. |
2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have type
```
float. |
We will see more about numeric types later in the tutorial.
```
-----
Division (/) always returns a float. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.