Introduction to Python
davidbpython.com
In-Class Exercises, Session 10
CLASSES - INSTANCES AND METHODS |
|
Ex. 10.1 | Define a class. |
Use the class statement with name MyClass (or you may substitute a name of your own choice). To fill the otherwise empty block, use the pass statement. Initialize an instance of the class and print its type to show that it is an instance of the class. |
|
Expected Output:
<class '__main__.MyClass'> |
|
Ex. 10.2 | Create an 'instance' method. |
Add to the class Hola below a new method, saludar(), that prints "bienvenidos a todos" (or whatever greeting you'd prefer) when it is called. |
|
class Hola:
""" una clase que is amigable """
# your code here
yo = Hola()
yo.saludar() # should print the greeting
|
|
Expected Output:
bienvenidos a todos |
|
Ex. 10.3 | Add argument and return value to method. |
Add the method doubleit() below, that doubles the value passed to it. |
|
class Numbers:
""" various number methods """
num = Numbers()
val = num.doubleit(5)
print(val) # 10
val2 = num.doubleit(100)
print(val2) # 200
|
|
Expected Output:
10 200 |
|
LAB 1 |
|
Ex. 10.4 | Create a class Time that has a method get_time() that returns the current time. Call as shown. |
(A string showing the current time can be obtained from the time module using time.ctime().) |
|
import time
# your code here
obj = Time()
print(obj.get_time()) # should show the current time
|
|
Expected Output:
Sat Oct 17 18:41:34 2020 (as your specific date and time) |
|
Ex. 10.5 | Create a class Random that has a method get_rand(val) that returns a random number from 1 to the specified value. Call as shown. |
(A random number can be generated with random.randint(x, y) where x and y are the minimum and maximum values.) |
|
import random
# your code here
obj = Random()
val = obj.get_rand(5) # random number from 1-5
print(val)
val2 = obj.get_rand(18) # random number from 1-18
print(val2)
|
|
Expected Output:
4 3 |
|
Ex. 10.6 | Create a class Math with method add() that takes two integer arguments and returns the values summed. |
# your code here
obj = Math()
mysum = obj.add(5, 10) # 15
print(mysum)
mysum2 = obj.add(100, 150) # 250
print(mysum2)
|
|
Expected Output:
15 250 |
|
CLASSES - CONSTRUCTOR, CLASS ATTRIBUTES AND METHODS |
|
Ex. 10.7 | Demonstration: note the unique identifier of self and an instance from a class. |
At the bottom of the code below, print obj, then call obj.something(), noting that this method prints self. Compare the hex codes that identify the instance. Use a print() statement to create a blank line. Next, print obj2 and call obj2.something(), and note the output, particularly the hex codes. |
|
class Do:
def something(self):
print(self)
obj = Do()
obj2 = Do()
# your code here
|
|
Expected Output:
<__main__.Do object at 0x10d648350> <__main__.Do object at 0x10d648350> <__main__.Do object at 0x10d648390> <__main__.Do object at 0x10d648390> |
|
Ex. 10.8 | Create an __init__() method. |
Add a method to the below class, __init__(self) that inside the function announces and prints the argument self, i.e. print(f'self: {self}'). Construct 2 new instances, and then print each instance. Put a blank line between each instance. |
|
class Be:
""" this class is something! """
obj1 = Be()
print(f'object: {obj1}')
print()
obj2 = Be()
print(f'object: {obj2})
|
|
Expected Output:
object: <__main__.Be object at 0x10d648250> self: <__main__.Be object at 0x10d648250> object: <__main__.Be object at 0x10d648a50> self: <__main__.Be object at 0x10d648a50> |
|
(Note that the above 0x hex codes will not be the same as mine, but the values in each pair should match.) |
|
Ex. 10.9 | Set an instance attribute in __init__(). |
Create a method __init__(self, num) that sets numin self as a .value attribute. At bottom, print obj.value to see the value. |
|
class Live:
""" a class that just wants to live """
# your __init__() code here
obj = Live(5)
# print obj.value here
|
|
Expected Output:
5 |
|
Ex. 10.10 | Create a "getter" method. |
Create a method get_value() that returns the .value attribute from the instance. |
|
class Say:
def __init__(self, val):
self.value = val
# your code here
obj = Say(100)
vl = obj.get_value()
print(vl) # 100
|
|
Expected Output:
100 |
|
Ex. 10.11 | Demonstrate class attributes. |
In the class below, set a class variable cvar to value 1000. Print the value of cvar in three places: 1) instance a (a.cvar); 2) instance b (b.cvar); 3) the class itself (Something.cvar) Also print the .attr attribute from each of the two instances. |
|
class Something:
# your class variable here
def __init__(self, xx):
self.attr = xx
a = Something('hi')
b = Something('there')
# print cvar in 3 places here
# print .attr from each of the two instances here
|
|
Expected Output:
1000 1000 1000 hi there |
|
Ex. 10.12 | Create a class method. |
Add a class method classincrement(cls) that uses its cls argument to increment the cattr class variable (cattr will be found to be an attribute of cls. Call classincrement() through the instance obj as well as through the class MyClass. The values printed below should both be 1. Before this can work as shown, however, you must decorate classincrement() with @classmethod. |
|
class MyClass:
cattr = 0
# your classincrement(cls) method here
obj = MyClass()
obj.classincrement()
print(obj.cattr) # should be 1
print(MyClass.cattr) # should be 1
|
|
Expected Output:
1 1 |
|
Ex. 10.13 | Create a static method. |
To the below class add the static method ftoc(temp) which converts a temperature in Fahrenheit to Celcius. The formula is (temp - 32) * 5 / 9 To be a static method, the method must not take self as an argument, and must be decorated with @staticmethod. |
|
class Forecast:
def __init__(self, forecast, high=0, low=0):
self.text = forecast
self.hightemp = high
self.lowtemp = low
def ftoc(temp):
return (temp - 32) * 5 / 9
t = Forecast('Light rain', high=62, low=48)
print(t.ftoc(32)) # 0.0
print(t.ftoc(212)) # 100.0
|
|
Expected Output:
0.0 100.0 |
|
LAB 2 |
|
Ex. 10.14 | Create class Counter, initialized with an integer as shown below. Set the attribute .counterval in __init__ so that it is available in the instance. |
# your code here
c = Counter(5)
print(c.counterval) # 5
|
|
Expected Output:
5 |
|
Ex. 10.15 | Update Counter with an .increment() method that increments the attribute value each time it is called. Call .increment() twice, then print the value of .counterval through the instance. |
class Counter:
def __init__(self, val):
self.counterval = val
# your code here
c = Counter(5)
c.increment()
c.increment()
print(c.counterval) # 7
|
|
Expected Output:
7 |
|
Ex. 10.16 | Update Counter with a show_value() method that returns the attribute value. |
class Counter:
def __init__(self, val):
self.counterval = val
def increment(self):
self.counterval = self.counterval + 1
# your code here
c = Counter(5)
c.increment()
c.increment()
print(c.counterval) # 7
|
|
Expected Output:
7 |
|
Ex. 10.17 | Set a class variable, 'increment_value', that specifies how much the increment() method should increase the attribute. Add this value to the .counterval attribute in increment(). |
class Counter:
# your class variable here
def __init__(self, val):
self.counterval = val
def increment(self):
self.counterval = self.counterval + 1
# add the value of increment_value here
c = Counter(5)
c.increment()
c.increment()
print(c.counterval) # 5 + (2 * increment_value)
|
|
Expected Output:
7 |
|
USEFUL MODULES |
|
Ex. 10.18 | Exploring documentation: math. |
Do a google search for python documentation. At the documentation page, choose Library Reference. Note all the many modules listed on this page -- these are the modules that are included in the Python standard distribution -- the Python install provided by python.org. Find the math module. Below, see if you can import math and then make use of one of the functions in the module. |
|
Ex. 10.19 | Featured module: zipfile. |
import zipfile as zp
myzip = zp.ZipFile('myzip.zip', 'w')
# add names of files in the current directory
myzip.write() # write 1st filename here
myzip.write() # write 2nd filename here
myzip.close()
print('done')
|
|
After running the above, check the session files directory -- you should see a new .zip file added. |
|
Ex. 10.20 | Featured module: time. |
import time
secs = time.time()
# print(time.ctime(secs))
# print(time.localtime(secs))
# time.sleep(5)
|
|
Ex. 10.21 | Featured module: datetime. |
import datetime as dt
# mydate = dt.date(2019, 9, 3)
# mydate = dt.date.today()
# mydatetime = dt.datetime(2019, 9, 3, 12, 5, 30)
# mydatetime = dt.datetime.now()
#secs = time.time()
#time_elements = time.localtime(secs)
#print(time_elements)
# myinterval = dt.timedelta(days=3, seconds=120)
# newdate = mydate + myinterval
# print(newdate)
# print(newdate.strftime('%Y-%m-%d'))
# dt.datetime.strptime('2019-03-03', '%Y-%m-%d')
|
|
Ex. 10.22 | Featured module: random. |
import random
myfloat = random.random()
# num = random.randint(10)
# num = random.randint(3,5)
# x = ['a', 'b', 'c']
# choice = random.choice(x)
|
|
Ex. 10.23 | Featured module: csv. |
import csv
fh = open('../dated_file.csv')
reader = csv.reader(fh)
for row in reader:
print(row)
fh.close()
# wfh = open('../newfile.csv', 'w', newline='')
# writer = csv.writer(wfh)
# writer.writerow(['a', 'b', 'c'])
# wfh.close()
# Again, please be advised that you will not see writes to a file
# until you close the file with fh.close() or until the program
# ends execution. This is particularly critical with Jupyter as
# it is basically a running program.
|
|
Ex. 10.24 | Featured module: openpyxl. |
(Note: if not using Anaconda Python, this module must be installed separately.) |
|
import openpyxl as ox
# read an Excel workbook from a file
# read_only=True will limit your actions to reading
wb = ox.load_workbook('../revenue.xlsx', read_only=True)
# show list of sheets within the workbook
print(wb.sheetnames)
# ['transactions']
# access a single sheet within the workbook
ws = wb['transactions']
# loop through the entire worksheet and look at each row
for row in ws.iter_rows():
# subscript out two fields from the row
col1 = row[0].value
col2 = row[1].value
# to skip rows (for example, headers) you can use min_row= argument:
for row in ws.iter_rows(min_row=2):
# subscript out two fields from the row
col1 = row[0].value
col2 = row[1].value
# note that older versions of openpyxl may use the skip_rows= argument instead of min_row=.
# access one cell by Excel cellname
c = ws['A2'] # 'cell' object
print(c.value) # the value in the cell
print(ws['B2'].value) # access value in one statement
|
|
Ex. 10.25 | Featured module: sqlite3. |
import sqlite3
conn = sqlite3.connect('../mydatabase.db')
cur = conn.cursor()
cur.execute("CREATE TABLE mytable (name TEXT, years INT, balance FLOAT)")
cur.execute("INSERT INTO mytable VALUES ('Joe', 23, 23.9)")
cur.execute("INSERT INTO mytable VALUES ('Marie', 19, 7.95)")
cur.execute("INSERT INTO mytable VALUES ('Zoe', 29, 17.5)")
conn.commit()
cur = conn.cursor()
rs = cur.execute('SELECT * FROM mytable')
for row in rs:
print(row)
|
|
Ex. 10.26 | Featured module: pandas data acquisition. |
(Note: if not using Anaconda Python, this module must be installed separately.) |
|
import pandas as pd
import sqlite3
df = pd.read_csv('../dated_file.csv')
# write DataFrame to excel
#df.to_excel('../dated_file.xls')
# read from database through query
# conn = sqlite3.connect('../testdb.db')
# df = pd.read_sql('SELECT * FROM test', conn)
|
|
Ex. 10.27 | pandas data management. |
df = pd.read_csv('../dated_file.csv')
# sum, average, etc. a column
# create a new column
# select rows thru a filter
# groupby aggregation
|
|
Ex. 10.28 | pandas visualization. |
# groupby bar chart
# weather temp line chart
|
|
Ex. 10.29 | Featured module: bs4. |
(Note: if not using Anaconda Python, this module must be installed separately.) |
|
import bs4
fh = open('../dormouse.html')
text = fh.read()
page = bs4.BeautifulSoup(text, 'html.parser')
print(page.title)
fh.close()
|
|
Ex. 10.30 | Featured module: requests. |
(Note: if not using Anaconda Python, bs4 must be installed separately.) |
|
import requests
import bs4
response = requests.get('http://www.nytimes.com')
page = bs4.BeautifulSoup(response.text, 'html.parser')
print(page.title)
|
|
Ex. 10.31 | Featured module: re. |
import re
line = 'a phone number: 213-298-1990'
matchobj = re.search(r'(\d\d\d)\-(\d\d\d)\-(\d\d\d\d)', line)
print(matchobj.group(1))
|
|
Ex. 10.32 | Featured module: subprocess. |
import subprocess
subprocess.call(['python', 'hello.py'])
# out = subprocess.check_output(['python', 'hello.py')
|
|
Ex. 10.33 | Featured module: textwrap. |
import textwrap
text = ("This is some really long text that we would like to wrap. "
"Wouldn't you know it, there's a module for that! ")
items = textwrap.wrap(text, 10)
print('\n'.join(items))
|
|