Upload
deirdre-whitehead
View
212
Download
0
Embed Size (px)
Citation preview
By: Chris Harvey
Python Classes
NamespacesA mapping from names to objectsDifferent namespaces have different
mappingsNamespaces have varying lifetimes
Name Object
a 5
b 8
c 13
Name Object
x 8
fibonacci
function
result 21
Name Object
abs function
range function
True 1
ScopesRegion of code with access to a specific
namespaceAt any point, several scopes can be accessedThe most local scope is accessed first
Name Object
a 5
b 8
c 13
Name Object
x 8
fibonacci
function
result 21
Name Object
abs function
range function
True 1
Class Definition SyntaxDefinition formed
by a block of statements
A new namespace is created during class definition
A class must be defined before usage
Class ObjectsClass definition
itself has attributes
Class definition can be instantiated
Initialization methods can be added to class definitions
Instance Objects
All attributes of class object exist on instance
Instance can have attributes that are different from the class definition
Method Objects
Methods can be referred to by a name and called later
When a method is called the object it is called on is passed as first argument
By convention, the calling object argument is named self
InheritanceA class can inherit the
attribute of another class or classes
A name is matched to the first base class found with depth-first, then left-to-right
Types can be checked using isinstance(object,type) and issubclass(type,baseType)
Private VariablesNo such thing as truly
private variables
By convention, an underscore denotes a private member
Two underscores prefixed and up to one suffixed indicates name mangling
IteratorsClasses that represent
collections can offer iterators
Special __iter__ and __next__ methods must be created for traversing collection
Next() raises a StopIteration exception when no more elements exist
GeneratorsCreation of iterators
can be simplified
Use keyword yield to designate elements of collection
All iterator functionality created automatically