2.1 KiB
2.1 KiB
[Index](index.md) | [Exercise 9.1](ex9_1.md) | [Exercise 9.3](ex9_3.md)
Exercise 9.2
Objectives:
- Learn how to create a Python package
Note
This exercise mostly just involves copying files on the file system. There shouldn't be a lot of coding.
(a) Making a Package
In previous exercises, you created the following files that were related to type-checked structures, reading data, and making tables:
structure.pyvalidate.pyreader.pytableformat.py
Your task is to take all of these files and move them into a package called structly.
To do that, follow these steps:
- Make a directory called
structly - Make an empty file
__init__.pyand put it in thestructlydirectory - Move the files
structure.py,validate.py,reader.py, andtableformat.pyinto thestructlydirectory. - Fix any import statements between modules (specifically, the
structuremodule depends onvalidate).
Once you've done that, modify the stock.py program so that it looks exactly like this
and that it works:
# stock.py
from structly.structure import Structure
class Stock(Structure):
name = String()
shares = PositiveInteger()
price = PositiveFloat()
@property
def cost(self):
return self.shares * self.price
def sell(self, nshares: PositiveInteger):
self.shares -= nshares
if __name__ == '__main__':
from structly.reader import read_csv_as_instances
from structly.tableformat import create_formatter, print_table
portfolio = read_csv_as_instances('Data/portfolio.csv', Stock)
formatter = create_formatter('text')
print_table(portfolio, ['name','shares','price'], formatter)
[Solution](soln9_2.md) | [Index](index.md) | [Exercise 9.1](ex9_1.md) | [Exercise 9.3](ex9_3.md)
>>> Advanced Python Mastery
... A course by dabeaz
... Copyright 2007-2023
. This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License