Skip to content

Commit 0ff02a7

Browse files
committed
Merge pull request UWPCE-PythonCert#87 from saschwafel/master
Added Generator Lab and Start on SparseArray
2 parents 13b1a98 + 8869c1a commit 0ff02a7

20 files changed

+879
-0
lines changed
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
Notes - November 18, 2014
2+
====================
3+
4+
5+
Subclassing is not for specialization, it's for reusing code
6+
7+
The subclass is in charge
8+
9+
10+
Multiple inheritance - inheriting from more than one class
11+
12+
class Combined(Super1, Super2, Super3):
13+
14+
method resolution order - class order of operations
15+
16+
is it an instance attribute?
17+
Is it a class attribute?
18+
Is it a superclass attribute?
19+
20+
Is it an attributed of the left-most superclass?
21+
Next?
22+
23+
Mixins - classes that are designed to add functionality to a class, but can't do much on its own
24+
25+
animal
26+
27+
mammal
28+
givebirth()
29+
30+
Bird
31+
layeggs()
32+
33+
Where do you put platypus?
34+
35+
Real world example: FloatCanvas
36+
37+
38+
39+
All of the lcass definitions we've been showing inherit from object
40+
41+
This is referred to as a "new style" class
42+
43+
Always subclass from Object
44+
45+
46+
super(): <--- use it to call a superclass method, rather than explicitly callin the unbound method on the superclass
47+
48+
read manpages on super()
49+
50+
Properties
51+
52+
Attributes are simple and concise
53+
54+
But what if you need to add extra behavior?
55+
56+
class C(object):
57+
_x = None
58+
@property
59+
def x(self):
60+
return self._x
61+
@x.setter
62+
def x(self, value):
63+
self._x = value
64+
65+
@ <----decoration
66+
67+
Syntax for wrapping up function with special syntax
68+
69+
getters/setters/deleters
70+
71+
72+
Static and Class Methods:
73+
74+
Static method is a method that doesn't get 'self'
75+
76+
@staticmethod
77+
def(a,b):
78+
return a+b
79+
80+
81+
Why are static methods useful? They aren't, usually.
82+
83+
99% of the time you just want a module-level function
84+
85+
Class Methods
86+
87+
A class method gets the class object, rather than an instance, as the first argument
88+
89+
Why? Unlike static methods, class methods are quite common. They are friendly to subclassing
90+
91+
Properties, Satic Methods, and Class Methods are powerful features of Python's OO model.
92+
93+
Descriptor Protocol!
94+
95+
Special Methods! MAgic Methods are the secret sauce to Python's Duck typing. Defining the appropriate special methods in your classes is how you make your classes behave like python Builtins.
96+
97+
__init__ <---special method
98+
99+
object.__str__ is what happens when you ask for a string version of an object, for example
100+
101+
102+
Protocols
103+
104+
THe set of special methods needed to emulate a particular type of Python object is called a protocol.
105+
106+
Your classes can "become" like Python builtins by implementing methods in a given protocol
107+
108+
109+
Use special methods when you want your class to act like a "standard" class in some way.
110+
111+
Look up the special methods you need and define them
112+
113+
Guide to Python's Magic Methods
114+
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
Notes - Nov 25, 2014
2+
3+
__iadd__
4+
5+
augmented assignment, used for in-place addition; changes object in place
6+
7+
Making your class behave like builtins!
8+
9+
callable classes
10+
11+
a_result = something(some_arguments)
12+
13+
something <---Class
14+
15+
__call__)*args, **kwargs)
16+
17+
if you define a __call__ method, that method will be used when code "calls" an instance of your class
18+
19+
Non-built-in sequence classes!
20+
21+
You can create a class that looks like a regular sequence, just add __len__, __getitem_, __setitem__, __delitem__, etc.
22+
23+
24+
Iterators and generators
25+
26+
What goes on in for loops?
27+
28+
iterators are what makes Python so readable
29+
30+
an_iterator.__iter__()
31+
32+
returns the iterator object itself
33+
34+
an_iterator.next()
35+
36+
returns next item until there are none, then returns StopIteration
37+
38+
39+
What do for loops do?
40+
41+
itertools -> build cool iterators out of sequences you have
42+
43+
44+
45+
Generators
46+
47+
generators give you the iterator immediately
48+
49+
50+
conceptually - iterators are about various ways to loop over data,
51+
generators generate the data on the fly
52+
53+
practically - you can use either one either way (and generator is a type of
54+
iterator
55+
56+
def a_generator_function(params):
57+
some_stuff
58+
yield something
59+
60+
61+
a function with 'yield' is a factory for a generator
62+
63+
gen_a = a_generator()
64+
gen_b a_generator()
65+
66+
67+
68+
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
Notes 11/02/2014
2+
====================
3+
4+
You can bind a function to a symbol and return/pass them to functions
5+
6+
Decorator - function takes function as an argument, gives a function as a return value
7+
8+
Rebinding the name of a function to the result of calling a decorator on that function is called decoration
9+
10+
@ <---special operator
11+
12+
Decorators can be used with anything that is callable
13+
14+
A decorator is a callable that takes a callable as an argument and returns a callable as a return value.
15+
16+
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
Notes - 12/9/2014
2+
====================
3+
4+
Unicode and the Persistence of Serialization
5+
---
6+
7+
Projects Due at the end of this week! - Friday
8+
9+
Anything is bytes <-- if it's stored on a disk or sent over a network, it's bytes
10+
11+
Unicode makes it easier to deal with bytes
12+
13+
Used to be able to fit everything into a two byte integer, (65,536 chars.)
14+
15+
Variety of encodings -> way of going between the canonical name of a character, and how it's stored in memory
16+
17+
Py2 strings are a sequence of bytes - Unicode strings are sequences of platonic characters
18+
19+
Platonic characters cannot be written to disk or network
20+
21+
22+
Python has both str and unicode
23+
24+
Two ways to work with binary data:
25+
26+
str and bytes() and bytearray
27+
28+
In Python 3 bytes and strings are completely different!
29+
30+
Unicode object lets you work with characters - all the same methods as the string object
31+
32+
Encoding is converting from unicode object to bytes
33+
34+
Decoding is converting from bytes to a unicode object
35+
36+
37+
import codects
38+
#encoding and decoding stuff
39+
40+
codecs.encode()
41+
codecs.decode()
42+
codecs.open() #better to use io.open
43+
44+
Use Unicode in your source files -
45+
46+
#-*- coding: utf-8 -*-
47+
48+
The Trick in Using Unicode - Be Consistent:
49+
50+
Always unicode, never Python strings
51+
52+
Do the decoding when you input your data
53+
54+
Decode on input
55+
56+
Encode on output
57+
58+
59+
get default encoding - sys.getdefaultencoding()
60+
61+
62+
from __future__ import unicode_literals #<----after running this line u'' is assumed!
63+
64+
-be aware that you can still get Python 2 strings from other places...
65+
66+
JSON Requires UTF-8!
67+
68+
In Python 3, all strings are unicode
69+
70+
Py3 has two distinct concepts:
71+
72+
text - uses str object
73+
binary data - uses bytes
74+
75+
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#!/usr/bin/python
2+
3+
from __future__ import unicode_literals
4+
from pprint import pprint
5+
import urllib2
6+
import simplejson as json
7+
8+
#user_local_data = json.load(urllib2.urlopen('http://freegeoip.net/json/'))
9+
user_local_data = json.load(urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?key=a648bf3844359d401197bcaa214dd01e0f8c0c6d623ec57f3716fbcafc8262bd&format=json'))
10+
11+
user_lat = user_local_data['latitude']
12+
user_long = user_local_data['longitude']
13+
14+
#print gathered lat/long
15+
#print user_lat,user_long
16+
17+
#print """
18+
#
19+
#You can get your latitude and longitude from http://www.latlong.net/
20+
#
21+
#"""
22+
23+
#user_lat = raw_input('Please enter your Latitude: \n')
24+
#user_long = raw_input('Please enter your Longitude: \n')
25+
26+
#user_lat = '47.653098'
27+
#user_long = '-122.353731'
28+
29+
lat_long_url = 'https://congress.api.sunlightfoundation.com/districts/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long)
30+
31+
congressional_district = json.load(urllib2.urlopen(lat_long_url))
32+
33+
34+
legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long)))
35+
36+
for i in legislators['results']:
37+
print i['last_name'] + ' ' + i['bioguide_id']
38+
39+
#All Legislators, irrespective of location
40+
41+
#House only
42+
#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?chamber=house&per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long)))
43+
44+
#All Legislators
45+
#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long)))
46+
47+
#print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n'
48+
49+
50+
#Prints Congressman/Congresswoman + First, Last
51+
52+
def find_legislators():
53+
54+
for i in legislators['results']:
55+
print i['last_name'] + ' ' + i['bioguide_id']
56+
#legislator_ids.append(i)
57+
58+
#find_legislators()
59+
60+
#votes_url = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/votes?voter_ids.{}__exists=true&apikey=15f4679bdc124cd6a2c6be8666253000')).format( __ THIS IS WHERE THE UNIQUE ID OF THE LEGISLATOR NEEDS TO BE __ )
61+
62+
#pprint(votes_url)
63+
64+
#def recent_votes():
65+
66+
##THIS IS WHERE YOU ARE GOING TO RETURN THE LAST 10 VOTES BY var = LEGISLATOR
67+
68+
def print_legislators():
69+
70+
for i in legislators['results']:
71+
72+
if i['chamber'] == 'house' and i['gender'] == 'M':
73+
print 'Congressman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] )
74+
if i['chamber'] == 'house' and i['gender'] == 'F':
75+
print 'Congresswoman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] )
76+
elif i['chamber'] == 'senate':
77+
print 'Senator {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] )
78+
79+
#print_legislators()
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
#List Current Members of Congress with GovTrack
3+
#congresspeople_url = 'https://www.govtrack.us/api/v2/role?current=true&limit=600'
4+
5+
#One Particular Congressman
6+
#url = 'https://www.govtrack.us/api/v2/person/400054'
7+
# this takes a python object and dumps it to a string which is a JSON
8+
# representation of that object
9+
data = json.load(urllib2.urlopen(congresspeople_url))
10+
11+
objects = data['objects']
12+
#for representative in objects:
13+
# print representative['person']['name'].encode('utf-8')
14+
#pprint(objects[0][person]['sortname'])
15+
16+
representatives = []
17+
18+
for i in objects:
19+
representatives.append(i['person']['sortname'].encode('utf-8'))
20+
21+
#representatives = sorted(representatives)
22+
#pprint(representatives)
23+

0 commit comments

Comments
 (0)