I'm writting these classes and a function to store file data for this database. I'm given a File, with a file owner# and a file number#. I want to move the extra file with the matching file owner and number from the Database and put it in the file owners list of the indicated owner. It returns None but it Raises a DuplicateIdError if the owner already has a the file with that file number#. It will raise a MissingIdError if the owner or file doesn't exist in the database. My question is, how do I call multiple instance-variables and methods from another class into my function (File Class and Owners Class to the Database class I'm currently in?
class File:
self.file_num
class Owners:
self.owner_id
self.owner_list
class Database:
def loan_book(self, owner_id, file_num):
extra_file = file # Calls file from File Class?
for i in self.owner_id: # Calls from Owners Class?
for j in self.owner_list: # Calls from Owners Class?
if extra_file == owner_id and file_num:
raise DuplicateIdError
elif extra_file != owner_id and file_num:
extra_file.append(self.owner_list)
else:
raise MissingIdError
Because you have instances of Owner
s and File
s, you'll need an initializer in your classes, aka __init__()
. Your database holds a reference to a list of owners. Then you can iterate through those owners to find the right one.
class File:
def __init__(self, num):
self.num = num
class Owner:
def __init__(self, id, files=[]):
self.id = id
self.files = files
def add_file(self, file_num):
extraFile = File(file_num)
self.files.append(extraFile)
class Database:
def __init__(self, owners=[]):
self.owners = owners
def loan_book(self, owner_id, file_num):
for owner in owners:
if owner.id == owner_id:
for file in owner.files:
if file.id == file_num:
raise DuplicateIdError
owner.add_file(file_num)
raise MissingIdError
Then, to make use of these, you could do something like such:
f = File(1)
owner1 = Owner(1, [f])
owner2 = Owner(2)
db = Database([owner1, owner2])
db.loan_book(2, 1) # Adds file with id 1 to owner2's list
db.loan_book(1, 1) # Raises DuplicateIdError
db.loan_book(3, 1) # Raises MissingIdError