class Package:
def __init__(self, name, address):
self.customer = name
self.pickuplocation = address
customers = []
customers.append(Package("John Doe","350 5th Ave"))
customers.append(Package("Jane Doe","100 7th Ave"))
customers.append(Package("Joe Daniels","11 1st Ave"))
for index, item in enumerate(customers):
print (index, item.customer, item.pickuplocation)
Output
0 John Doe 350 5th Ave
1 Jane Doe 100 7th Ave
2 Joe Daniels 11 1st Ave
I’m attempting to emulate an array of JavaScript class instances similar to the ‘family’ example in JS Objects. Obviously not the same in Python, so I’m having to wrap my head around this. Obviously the instances are not dictionaries. Am I correct?
For example, item above has attributes, but no keys() method.
Please apprise me of any errors in my thinking, here. Thank you. The above code is giving a sequential number but I don’t really know for certain if anyt rules are being broken. I struggled with it for a good long while to get it this far.
I think attributes like name and address should be attributes of the object, they aren’t just data, they are part of the logic. But sure, it’s equivalent for the most part
Linear search can be a problem at a large scale, it would be better to use dictionaries and register each package with a name and a destination
For id numbers you could use uuid4 which is very unlikely to generate the same id twice, eliminating the need for a counter
>>> from uuid import uuid4
>>> print(uuid4())
30b85606-9316-4df7-be20-8c85e2b5df4a
Plus, it looks fancy… :D[quote=“mtf, post:13, topic:44037”]
None
Name: Jane Doe
Address: 100 7th Ave
Data: {'order_number': 2}
Still not sure about the search option though. Unclear how to set up the instances in an organized way that permits some duplication. That’s why I selected the list object to contain the instance objects.
Avoid using __dict__ directly, you’re not meant to use any of the “magic names” directly.
You’ll really have to rethink this line:
#- find_customer and search
do they really need to search through every package?
You could let customer names be keys to which packages are getting delivered to them instead. #-
Do you really need two names referring to the index?
Here’s my take, in two files. One for the module and another for using it to produce similar output to yours.
Main differences:
Not treating class attributes like unordered pairs
“Searches” are look-ups
Broke out customers into its own class
Can create instances of Database instead of one global
# File: demo.py
from mtf import Database
db = Database()
db.add_package('John Doe', '350 5th Ave')
db.add_package("Jane Doe", "100 7th Ave")
db.add_package("Joe Daniels", "11 1st Ave")
names = ['Jane Doh', 'Jane Doe']
for name in names:
try:
packages = db.get_packages_by_name(name)
for package in packages:
print(package)
except KeyError:
print('{} not in database.'.format(name))
output:
Jane Doh not in database.
Name: Jane Doe
Address: 100 7th Ave
Order_id: 339f10b3-25d2-4f1f-afbe-f25304d89466
# File: mtf.py
from uuid import uuid4
class DatabaseKeyError(KeyError):
pass
class Customer:
def __init__(self, name):
self.name = name
self.packages = []
def __str__(self):
return self.name
class Package:
def __init__(self, customer, address):
self.customer = customer
self.address = address
self.order_id = uuid4()
def __str__(self):
return "Name: {customer}\nAddress: {address}\nOrder_id: {order_id}" \
.format_map(vars(self))
class Database:
def __init__(self):
self.customers = {}
self.packages = {}
def add_package(self, name, address):
# Add customer to database if it's new
if name not in self.customers:
self.customers[name] = Customer(name)
customer = self.customers[name]
# Associate package with customer object
package = Package(customer, address)
customer.packages.append(package)
# And also make it available for look-up by order-id
self.packages[package.order_id] = package
def get_package_by_id(self, order_id):
return self.packages[order_id]
def get_packages_by_name(self, name):
if name not in self.customers:
raise DatabaseKeyError('{} is not a known customer'.format(name))
return self.customers[name].packages
Expertly written and presented. Thank you! There is much to learn from this. I’ll be studying and modeling until I can cement the many concepts represented in this implementation.
Don’t read too much into it, I’m just rebelling against the looping-through-attributes and linear search. Other than that there’s no plan what-so-ever there
To take it further one would need to consider what operations need to be supported and how well they need to perform.
And, it really should leverage some actual database backend, unless it’s just meant to support operations for some algorithm.
For some reason, Python wouldn’t let me return index so I fudged it. Might have been my implementation…
Wondering if I should keep ironing out wrinkles in the above code, or abandon it. Seems a waste to get this far with many in’s and out’s yet to uncover. Hope you won’t mind if I pose more questions in this regard at some later juncture.