Text stringlengths 1 9.41k |
|---|
For example, given the following file, person.py:
```
class person:
...
```
we need to go through the module to fetch the class as usual:
```
import person # Import module
x = person.person() # Class within module
```
Although this path may look redundant, it’s required: `person... |
Saying just person gets the module, not the class,
```
unless the from statement is used:
```
from person import person # Get class from module
x = person() # Use class name
```
As with any other variable, we can never see a class in a file without first importing and
somehow fetching it... |
If this seems confusing, don’t use the same
name for a module and a class within it. |
In fact, common convention in Python dictates
that class names should begin with an uppercase letter, to help make them more
distinct:
```
import person # Lowercase for modules
x = person.Person() # Uppercase for classes
```
Also, keep in mind that although classes and modules are both... |
We’ll say more about such
distinctions later in this part of the book.
**|**
-----
###### Classes Can Intercept Python Operators
Let’s move on to the third major difference between classes and modules: operator
overloading. |
In simple terms, operator overloading lets objects coded with classes intercept and respond to operations that work on built-in types: addition, slicing, printing, qualification, and so on. |
It’s mostly just an automatic dispatch mechanism—
expressions and other built-in operations route control to implementations in classes.
Here, too, there is nothing similar in modules: modules can implement function calls,
but not the behavior of expressions.
Although we could implement all class behavior as method fu... |
Moreover,
because operator overloading makes our own objects act like built-ins, it tends to foster
object interfaces that are more consistent and easier to learn, and it allows class-based
objects to be processed by code written to expect a built-in type’s interface. |
Here is a
quick rundown of the main ideas behind overloading operators:
- Methods named with double underscores (__X__) are special hooks. |
Python
operator overloading is implemented by providing specially named methods to
intercept operations. |
The Python language defines a fixed and unchangeable mapping from each of these operations to a specially named method.
- Such methods are called automatically when instances appear in built-in
**operations. |
For instance, if an instance object inherits an __add__ method, that**
method is called whenever the object appears in a `+ expression. |
The method’s`
return value becomes the result of the corresponding expression.
- Classes may override most built-in type operations. |
There are dozens of special
operator overloading method names for intercepting and implementing nearly every operation available for built-in types. |
This includes expressions, but also basic
operations like printing and object creation.
- There are no defaults for operator overloading methods, and none are
**required. |
If a class does not define or inherit an operator overloading method, it**
just means that the corresponding operation is not supported for the class’s instances. |
If there is no __add__, for example, + expressions raise exceptions.
- Operators allow classes to integrate with Python’s object model. |
By overloading type operations, user-defined objects implemented with classes can act just
like built-ins, and so provide consistency as well as compatibility with expected
interfaces.
Operator overloading is an optional feature; it’s used primarily by people developing
tools for other Python programmers, not by appli... |
And, candidly, you
probably shouldn’t try to use it just because it seems “cool.” Unless a class needs to
mimic built-in type interfaces, it should usually stick to simpler named methods. |
Why
would an employee database application support expressions like * and +, for example?
Named methods like giveRaise and promote would usually make more sense.
**|**
-----
Because of this, we won’t go into details on every operator overloading method available
in Python in this book. |
Still, there is one operator overloading method you are likely
to see in almost every realistic Python class: the __init__ method, which is known as
the constructor method and is used to initialize objects’ state. |
You should pay special
attention to this method, because __init__, along with the self argument, turns out
to be a key requirement to understanding most OOP code in Python.
###### A Third Example
On to another example. |
This time, we’ll define a subclass of SecondClass that implements three specially named attributes that Python will call automatically:
- __init__ is run when a new instance object is created (self is the new ThirdClass
object).[*]
- __add__ is run when a ThirdClass instance appears in a + expression.
- __str__ i... |
Here’s the new subclass:
`>>> class ThirdClass(SecondClass):` _# Inherit from SecondClass_
`... def __init__(self, value):` _# On "ThirdClass(value)"_
```
... self.data = value
```
`... |
def __add__(self, other):` _# On "self + other"_
```
... return ThirdClass(self.data + other)
```
`... def __str__(self):` _# On "print(self)", "str()"_
```
... |
return '[ThirdClass: %s]' % self.data
```
`... def mul(self, other):` _# In-place change: named_
```
... |
self.data *= other
...
```
`>>> a = ThirdClass('abc')` _# __init__ called_
`>>> a.display()` _# Inherited method called_
```
Current value = "abc"
```
`>>> print(a)` _# __str__: returns display string_
```
[ThirdClass: abc]
```
`>>> b = a + 'xyz'` _# __add__: makes a new instance_
`>>> b.display()` _# b has al... |
See Chapter 23 for more details.
**|**
-----
```
ThirdClass “is a” SecondClass, so its instances inherit the customized display method
```
from SecondClass. |
This time, though, ThirdClass creation calls pass an argument (e.g.,
“abc”). This argument is passed to the value argument in the __init__ constructor and
assigned to self.data there. |
The net effect is that ThirdClass arranges to set the data
attribute automatically at construction time, instead of requiring setdata calls after the
fact.
Further, ThirdClass objects can now show up in + expressions and print calls. |
For +,
Python passes the instance object on the left to the self argument in __add__ and the
value on the right to other, as illustrated in Figure 26-3; whatever __add__ returns becomes the result of the + expression. |
For print, Python passes the object being printed
to self in __str__; whatever string this method returns is taken to be the print string
for the object. |
With __str__ we can use a normal print to display objects of this class,
instead of calling the special display method.
_Figure 26-3. |
In operator overloading, expression operators and other built-in operations performed_
_on class instances are mapped back to specially named methods in the class. |
These special methods_
_are optional and may be inherited as usual. |
Here, a + expression triggers the __add__ method._
Specially named methods such as __init__, __add__, and __str__ are inherited by subclasses and instances, just like any other names assigned in a class. |
If they’re not coded
in a class, Python looks for such names in all its superclasses, as usual. |
Operator overloading method names are also not built-in or reserved words; they are just attributes
that Python looks for when objects appear in various contexts. |
Python usually calls
them automatically, but they may occasionally be called by your code as well; the
```
__init__ method, for example, is often called manually to trigger superclass construc
```
tors (more on this later).
Notice that the __add__ method makes and returns a new instance object of its class,
by calling... |
By contrast, mul _changes the current instance_
object in-place, by reassigning the self attribute. |
We could overload the * expression
to do the latter, but this would be too different from the behavior of * for built-in types
such as numbers and strings, for which it always makes new objects. |
Common practice
dictates that overloaded operators should work the same way that built-in operator
implementations do. |
Because operator overloading is really just an expression-tomethod dispatch mechanism, though, you can interpret operators any way you like in
your own class objects.
**|**
-----
###### Why Use Operator Overloading?
As a class designer, you can choose to use operator overloading or not. |
Your choice
simply depends on how much you want your object to look and feel like built-in types.
As mentioned earlier, if you omit an operator overloading method and do not inherit
it from a superclass, the corresponding operation will not be supported for your instances; if it’s attempted, an exception will be thrown... |
For simpler
classes, you might not use overloading at all, and would rely instead on explicit method
calls to implement your objects’ behavior.
On the other hand, you might decide to use operator overloading if you need to pass
a user-defined object to a function that was coded to expect the operators available on
a b... |
Implementing the same operator set in your
class will ensure that your objects support the same expected object interface and so
are compatible with the function. |
Although we won’t cover every operator overloading
method in this book, we’ll see some additional operator overloading techniques in
action in Chapter 29.
One overloading method we will explore here is the `__init__ constructor method,`
which seems to show up in almost every realistic class. |
Because it allows classes to fill
out the attributes in their newly created instances immediately, the constructor is useful
for almost every kind of class you might code. |
In fact, even though instance attributes
are not declared in Python, you can usually find out which attributes an instance will
have by inspecting its class’s __init__ method.
###### The World’s Simplest Python Class
We’ve begun studying class statement syntax in detail in this chapter, but I’d again
like to remind y... |
In fact, we can
create a class with nothing in it at all. |
The following statement makes a class with no
attributes attached (an empty namespace object):
`>>> class rec: pass` _# Empty namespace object_
We need the no-operation pass statement (discussed in Chapter 13) here because we
don’t have any methods to code. |
After we make the class by running this statement
interactively, we can start attaching attributes to the class by assigning names to it
completely outside of the original class statement:
`>>> rec.name = 'Bob'` _# Just objects with attributes_
```
>>> rec.age = 40
```
**|**
-----
And, after we’ve created these ... |
When used this way, a class is roughly similar to a “struct” in C, or a
“record” in Pascal. |
It’s basically an object with field names attached to it (we can do
similar work with dictionary keys, but it requires extra characters):
`>>> print(rec.name)` _# Like a C struct or a record_
```
Bob
```
Notice that this works even though there are no instances of the class yet; classes are
objects in their own rig... |
In fact, they are just self-contained
namespaces, so as long as we have a reference to a class, we can set or change its
attributes anytime we wish. |
Watch what happens when we do create two instances,
though:
`>>> x = rec()` _# Instances inherit class names_
```
>>> y = rec()
```
These instances begin their lives as completely empty namespace objects. |
Because they
remember the class from which they were made, though, they will obtain the attributes
we attached to the class by inheritance:
`>>> x.name, y.name` _# name is stored on the class only_
```
('Bob', 'Bob')
```
Really, these instances have no attributes of their own; they simply fetch the name attribute f... |
If we do assign an attribute to an instance,
though, it creates (or changes) the attribute in that object, and no other—attribute
references kick off inheritance searches, but attribute assignments affect only the objects in which the assignments are made. |
Here, x gets its own name, but y still inherits
the name attached to the class above it:
`>>> x.name = 'Sue'` _# But assignment changes x only_
```
>>> rec.name, x.name, y.name
('Bob', 'Sue', 'Bob')
```
In fact, as we’ll explore in more detail in Chapter 28, the attributes of a namespace
object are usually implem... |
If you know where to look,
you can see this explicitly.
For example, the __dict__ attribute is the namespace dictionary for most class-based
objects (some classes may also define attributes in __slots__, an advanced and seldomused feature that we’ll study in Chapters 30 and 31). |
The following was run in Python
3.0; the order of names and set of __X__ internal names present can vary from release
to release, but the names we assigned are present in all:
```
>>> rec.__dict__.keys()
['__module__', 'name', 'age', '__dict__', '__weakref__', '__doc__']
>>> list(x.__dict__.keys())
['name']
``... |
Each instance has a link to its class for
inheritance, though—it’s called __class__, if you want to inspect it:
```
>>> x.__class__
<class '__main__.rec'>
```
Classes also have a __bases__ attribute, which is a tuple of their superclasses:
`>>> rec.__bases__` _# () empty tuple in Python 2.6_
```
(<class 'object... |
Classes and instances are just namespace objects, with attributes
created on the fly by assignment. |
Those assignments usually happen within the class
statements you code, but they can occur anywhere you have a reference to one of the
objects in the tree.
Even methods, normally created by a def nested in a class, can be created completely
independently of any class object. |
The following, for example, defines a simple function
outside of any class that takes one argument:
```
>>> def upperName(self):
```
`... |
return self.name.upper()` _# Still needs a self_
There is nothing about a class here yet—it’s a simple function, and it can be called as
such at this point, provided we pass in an object with a name attribute (the name self
does not make this special in any way):
`>>> upperName(x)` _# Call as a simple function_
```
... |
They can be called as either functions or methods, and Python can neither guess nor
assume that a simple function might eventually become a class method. |
The main reason for the explicit
```
self argument, though, is to make the meanings of names more obvious: names not referenced through
self are simple variables, while names referenced through self are obviously instance attributes.
```
**|**
-----
`>>> rec.method(x)` _# Can call through instance or class_
```
... |
The point again, though, is that
they don’t have to be; OOP in Python really is mostly about looking up attributes in
linked namespace objects.
###### Classes Versus Dictionaries
Although the simple classes of the prior section are meant to illustrate class model
basics, the techniques they employ can also be used fo... |
For example, Chapter 8 showed how to use dictionaries to record properties of entities in our programs.
It turns out that classes can serve this role, too—they package information like dictionaries, but can also bundle processing logic in the form of methods. |
For reference,
here is the example for dictionary-based records we used earlier in the book:
```
>>> rec = {}
```
`>>> rec['name'] = 'mel'` _# Dictionary-based record_
```
>>> rec['age'] = 45
>>> rec['job'] = 'trainer/writer'
>>>
>>> print(rec['name'])
mel
```
This code emulates tools like records in othe... |
As we just saw, though, there
are also multiple ways to do the same with classes. |
Perhaps the simplest is this—trading
keys for attributes:
```
>>> class rec: pass
...
```
`>>> rec.name = 'mel'` _# Class-based record_
```
>>> rec.age = 45
>>> rec.job = 'trainer/writer'
>>>
>>> print(rec.age)
40
```
This code has substantially less syntax than the dictionary equivalent. |
It uses an empty
```
class statement to generate an empty namespace object. |
Once we make the empty
```
class, we fill it out by assigning class attributes over time, as before.
This works, but a new class statement will be required for each distinct record we will
need. |
Perhaps more typically, we can instead generate instances of an empty class to
represent each distinct entity:
```
>>> class rec: pass
...
```
`>>> pers1 = rec()` _# Instance-based records_
```
>>> pers1.name = 'mel'
>>> pers1.job = 'trainer'
```
**|**
-----
```
>>> pers1.age = 40
>>>
>>> pers2 = re... |
Instances start out life empty, just like
classes. We then fill in the records by assigning to attributes. This time, though, there
are two separate objects, and hence two separate name attributes. |
In fact, instances of
the same class don’t even have to have the same set of attribute names; in this example,
one has a unique `age name. |
Instances really are distinct namespaces, so each has a`
distinct attribute dictionary. |
Although they are normally filled out consistently by class
methods, they are more flexible than you might expect.
Finally, we might instead code a more full-blown class to implement the record and its
processing:
```
>>> class Person:
```
`... |
def __init__(self, name, job):` _# Class = Data + Logic_
```
... self.name = name
... self.job = job
... def info(self):
... |
return (self.name, self.job)
...
>>> rec1 = Person('mel', 'trainer')
>>> rec2 = Person('vls', 'developer')
>>>
>>> rec1.job, rec2.info()
('trainer', ('vls', 'developer'))
```
This scheme also makes multiple instances, but the class is not empty this time: we’ve
added logic (methods) to initialize instances... |
The constructor imposes some consistency on instances here by always
setting the name and job attributes. |
Together, the class’s methods and instance attributes
create a package, which combines both data and logic.
We could further extend this code by adding logic to compute salaries, parse names,
and so on. |
Ultimately, we might link the class into a larger hierarchy to inherit an
existing set of methods via the automatic attribute search of classes, or perhaps even
store instances of the class in a file with Python object pickling to make them persistent.
In fact, we will—in the next chapter, we’ll expand on this analogy ... |
We studied the syntax
of the class statement, and we saw how to use it to build up a class inheritance tree.
We also studied how Python automatically fills in the first argument in method functions, how attributes are attached to objects in a class tree by simple assignment, and
how specially named operator overloading... |
After that, we’ll continue our look at class coding,
taking a second pass over the model to fill in some of the details that were omitted here
to keep things simple. |
First, though, let’s work through a quiz to review the basics we’ve
covered so far.
###### Test Your Knowledge: Quiz
1. How are classes related to modules?
2. |
How are instances and classes created?
3. Where and how are class attributes created?
4. Where and how are instance attributes created?
5. What does self mean in a Python class?
6. |
How is operator overloading coded in a Python class?
7. When might you want to support operator overloading in your classes?
8. Which operator overloading method is most commonly used?
9. |
What are the two key concepts required to understand Python OOP code?
###### Test Your Knowledge: Answers
1. |
Classes are always nested inside a module; they are attributes of a module object.
Classes and modules are both namespaces, but classes correspond to statements
(not entire files) and support the OOP notions of multiple instances, inheritance,
and operator overloading. |
In a sense, a module is like a single-instance class, without inheritance, which corresponds to an entire file of code.
2. |
Classes are made by running class statements; instances are created by calling a
class as though it were a function.
**|**
-----
3. |
Class attributes are created by assigning attributes to a class object. |
They are normally generated by top-level assignments nested in a class statement—each name
assigned in the `class statement block becomes an attribute of the class object`
(technically, the `class statement scope morphs into the class object’s attribute`
namespace). |
Class attributes can also be created, though, by assigning attributes
to the class anywhere a reference to the class object exists—i.e., even outside the
```
class statement.
```
4. |
Instance attributes are created by assigning attributes to an instance object. |
They
are normally created within class method functions inside the class statement by
assigning attributes to the self argument (which is always the implied instance).
Again, though, they may be created by assignment anywhere a reference to the
instance appears, even outside the `class statement. |
Normally, all instance`
attributes are initialized in the `__init__ constructor method; that way, later`
method calls can assume the attributes already exist.
5. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.