Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
7e2e1d4
Class notes and lab for 11/18
saschwafel Nov 19, 2014
a30fb6f
Adding adding, mul, functions; adding tests
Nov 25, 2014
b7e95ab
Adding session08 labs and notes
saschwafel Nov 26, 2014
87c8460
Starting on 'Informed Voter' Project, getting a .json return value, s…
Nov 29, 2014
64d91a9
Wasn't able to finish labs, added some work to project. Generator lab…
Dec 2, 2014
3a09711
Adding class notes and in-class lab
saschwafel Dec 3, 2014
d26d860
Adding fix to return list of representatives
Dec 4, 2014
05689de
Merge branch 'master' of https://github.com/saschwafel/IntroToPython
Dec 4, 2014
51941f5
Messing with another API, return values based on lat/long
Dec 5, 2014
b295b04
Fixing printing and adding some verbiage. Make sure to add an if/else…
Dec 6, 2014
d19bde9
Splitting project between APIs, fixed title/gender printing
saschwafel Dec 6, 2014
6cf5b7a
Fixing the printing of the legislator to return title, first, last, t…
saschwafel Dec 6, 2014
749c6ae
Need to fix unicode in order for all legislators to print successfully
saschwafel Dec 6, 2014
cd036a2
May have fixed unicode errors by adding from __future__ line, now try…
saschwafel Dec 10, 2014
81e85d3
adding class notes and beginning of unicode lab
saschwafel Dec 10, 2014
34e31c5
Changing API for geolocation, working on why printing the complete li…
Dec 10, 2014
4257e2f
String formatting fixed NoneType issues
Dec 10, 2014
082c2ec
Troubleshooting geolocation
Dec 11, 2014
8869c1a
Final commit of project files.
Dec 12, 2014
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions Students/SSchwafel/Notes/11182014.notes
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
Notes - November 18, 2014
====================


Subclassing is not for specialization, it's for reusing code

The subclass is in charge


Multiple inheritance - inheriting from more than one class

class Combined(Super1, Super2, Super3):

method resolution order - class order of operations

is it an instance attribute?
Is it a class attribute?
Is it a superclass attribute?

Is it an attributed of the left-most superclass?
Next?

Mixins - classes that are designed to add functionality to a class, but can't do much on its own

animal

mammal
givebirth()

Bird
layeggs()

Where do you put platypus?

Real world example: FloatCanvas



All of the lcass definitions we've been showing inherit from object

This is referred to as a "new style" class

Always subclass from Object


super(): <--- use it to call a superclass method, rather than explicitly callin the unbound method on the superclass

read manpages on super()

Properties

Attributes are simple and concise

But what if you need to add extra behavior?

class C(object):
_x = None
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value

@ <----decoration

Syntax for wrapping up function with special syntax

getters/setters/deleters


Static and Class Methods:

Static method is a method that doesn't get 'self'

@staticmethod
def(a,b):
return a+b


Why are static methods useful? They aren't, usually.

99% of the time you just want a module-level function

Class Methods

A class method gets the class object, rather than an instance, as the first argument

Why? Unlike static methods, class methods are quite common. They are friendly to subclassing

Properties, Satic Methods, and Class Methods are powerful features of Python's OO model.

Descriptor Protocol!

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.

__init__ <---special method

object.__str__ is what happens when you ask for a string version of an object, for example


Protocols

THe set of special methods needed to emulate a particular type of Python object is called a protocol.

Your classes can "become" like Python builtins by implementing methods in a given protocol


Use special methods when you want your class to act like a "standard" class in some way.

Look up the special methods you need and define them

Guide to Python's Magic Methods

68 changes: 68 additions & 0 deletions Students/SSchwafel/Notes/11252014.notes
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
Notes - Nov 25, 2014

__iadd__

augmented assignment, used for in-place addition; changes object in place

Making your class behave like builtins!

callable classes

a_result = something(some_arguments)

something <---Class

__call__)*args, **kwargs)

if you define a __call__ method, that method will be used when code "calls" an instance of your class

Non-built-in sequence classes!

You can create a class that looks like a regular sequence, just add __len__, __getitem_, __setitem__, __delitem__, etc.


Iterators and generators

What goes on in for loops?

iterators are what makes Python so readable

an_iterator.__iter__()

returns the iterator object itself

an_iterator.next()

returns next item until there are none, then returns StopIteration


What do for loops do?

itertools -> build cool iterators out of sequences you have



Generators

generators give you the iterator immediately


conceptually - iterators are about various ways to loop over data,
generators generate the data on the fly

practically - you can use either one either way (and generator is a type of
iterator

def a_generator_function(params):
some_stuff
yield something


a function with 'yield' is a factory for a generator

gen_a = a_generator()
gen_b a_generator()




16 changes: 16 additions & 0 deletions Students/SSchwafel/Notes/12022014.notes
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Notes 11/02/2014
====================

You can bind a function to a symbol and return/pass them to functions

Decorator - function takes function as an argument, gives a function as a return value

Rebinding the name of a function to the result of calling a decorator on that function is called decoration

@ <---special operator

Decorators can be used with anything that is callable

A decorator is a callable that takes a callable as an argument and returns a callable as a return value.


75 changes: 75 additions & 0 deletions Students/SSchwafel/Notes/12092014.notes
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
Notes - 12/9/2014
====================

Unicode and the Persistence of Serialization
---

Projects Due at the end of this week! - Friday

Anything is bytes <-- if it's stored on a disk or sent over a network, it's bytes

Unicode makes it easier to deal with bytes

Used to be able to fit everything into a two byte integer, (65,536 chars.)

Variety of encodings -> way of going between the canonical name of a character, and how it's stored in memory

Py2 strings are a sequence of bytes - Unicode strings are sequences of platonic characters

Platonic characters cannot be written to disk or network


Python has both str and unicode

Two ways to work with binary data:

str and bytes() and bytearray

In Python 3 bytes and strings are completely different!

Unicode object lets you work with characters - all the same methods as the string object

Encoding is converting from unicode object to bytes

Decoding is converting from bytes to a unicode object


import codects
#encoding and decoding stuff

codecs.encode()
codecs.decode()
codecs.open() #better to use io.open

Use Unicode in your source files -

#-*- coding: utf-8 -*-

The Trick in Using Unicode - Be Consistent:

Always unicode, never Python strings

Do the decoding when you input your data

Decode on input

Encode on output


get default encoding - sys.getdefaultencoding()


from __future__ import unicode_literals #<----after running this line u'' is assumed!

-be aware that you can still get Python 2 strings from other places...

JSON Requires UTF-8!

In Python 3, all strings are unicode

Py3 has two distinct concepts:

text - uses str object
binary data - uses bytes


79 changes: 79 additions & 0 deletions Students/SSchwafel/Project/Draft_InformedVoter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#!/usr/bin/python

from __future__ import unicode_literals
from pprint import pprint
import urllib2
import simplejson as json

#user_local_data = json.load(urllib2.urlopen('http://freegeoip.net/json/'))
user_local_data = json.load(urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?key=a648bf3844359d401197bcaa214dd01e0f8c0c6d623ec57f3716fbcafc8262bd&format=json'))

user_lat = user_local_data['latitude']
user_long = user_local_data['longitude']

#print gathered lat/long
#print user_lat,user_long

#print """
#
#You can get your latitude and longitude from http://www.latlong.net/
#
#"""

#user_lat = raw_input('Please enter your Latitude: \n')
#user_long = raw_input('Please enter your Longitude: \n')

#user_lat = '47.653098'
#user_long = '-122.353731'

lat_long_url = 'https://congress.api.sunlightfoundation.com/districts/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long)

congressional_district = json.load(urllib2.urlopen(lat_long_url))


legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long)))

for i in legislators['results']:
print i['last_name'] + ' ' + i['bioguide_id']

#All Legislators, irrespective of location

#House only
#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?chamber=house&per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long)))

#All Legislators
#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long)))

#print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n'


#Prints Congressman/Congresswoman + First, Last

def find_legislators():

for i in legislators['results']:
print i['last_name'] + ' ' + i['bioguide_id']
#legislator_ids.append(i)

#find_legislators()

#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 __ )

#pprint(votes_url)

#def recent_votes():

##THIS IS WHERE YOU ARE GOING TO RETURN THE LAST 10 VOTES BY var = LEGISLATOR

def print_legislators():

for i in legislators['results']:

if i['chamber'] == 'house' and i['gender'] == 'M':
print 'Congressman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] )
if i['chamber'] == 'house' and i['gender'] == 'F':
print 'Congresswoman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] )
elif i['chamber'] == 'senate':
print 'Senator {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] )

#print_legislators()
23 changes: 23 additions & 0 deletions Students/SSchwafel/Project/GovTrack_InformedVoter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

#List Current Members of Congress with GovTrack
#congresspeople_url = 'https://www.govtrack.us/api/v2/role?current=true&limit=600'

#One Particular Congressman
#url = 'https://www.govtrack.us/api/v2/person/400054'
# this takes a python object and dumps it to a string which is a JSON
# representation of that object
data = json.load(urllib2.urlopen(congresspeople_url))

objects = data['objects']
#for representative in objects:
# print representative['person']['name'].encode('utf-8')
#pprint(objects[0][person]['sortname'])

representatives = []

for i in objects:
representatives.append(i['person']['sortname'].encode('utf-8'))

#representatives = sorted(representatives)
#pprint(representatives)

Loading