So I’ve wrote a program that will take a user’s input and save it as an address label. Now I’m supposed to rewrite the program and use classes instead of functions, and I’m a bit lost in what I should turn into classes vs what I should leave as functions. I’ll post my code below. Any help would be greatly appreciated!
def save_file():
while True:
try:
new_file = input("Please type the name of your new file with extension.")
return new_file
break
except Exception as e:
print("An error has occured.")
print("Please try again.")
return None
def address_input():
while True:
try:
fn = input("Your first name: ")
mi = input("Your middle name/initial: ")
ln = input("Your last name: ")
street_add1 = input("First part of your street address: ")
street_add2 = input("Apartment # or secondary identifier if applicable otherwise hit enter: ")
city = input("Your city: ")
state = input("Your state: ")
zip_code = input("Your ZIP: ")
phone_num = input("Your Phone number: ")
label_line1 = f"{fn} {mi} {ln} - {phone_num}\n"
label_line2 = f"{street_add1} {street_add2}\n"
label_line3 = f"{city} {state} {zip_code}\n"
return label_line1, label_line2, label_line3
break
except Exception as e:
print("Information not collected, please try again")
return None
def write_file(new_file, label_line1, label_line2, label_line3):
while True:
try:
with open(new_file, 'w') as file:
file.write(label_line1)
file.write(label_line2)
file.write(label_line3)
print(f" {new_file} was written succesfully.")
break
except FileNotFoundError as e:
print(f"File not found: {e}")
except IOError as e:
print(f"An error has occured, file not written. Please try again")
def preview(label_line1, label_line2, label_line3):
print("Your address label preview: ")
print(str(label_line1))
print(str(label_line2))
print(str(label_line3))
def main():
while True:
new_file_name = save_file()
if new_file_name is not None:
label_line1, label_line2, label_line3 = address_input()
write_file(new_file_name, label_line1, label_line2, label_line3)
preview(label_line1, label_line2, label_line3)
break
main()
There is a lot written about this so these are just some quick suggestions off the top of my head.
If you haven’t seen the term before, designing programs around classes is called “object-oriented programming”, or “OOP”. That may help you find relevant search results. The way your program is written now is sometimes called “procedural” design - it focuses on what actions need to happen in what order, and splits each step (procedure) into smaller steps (sub-procedures). Object-oriented design focuses on grouping related data and operations on that data together into units (objects).
So one way to start is to look closely at the data your program is using. In your assignment there is a description of the program to write and what it should do. Go through the description and look for all the nouns - the subjects or objects the program is supposed to act on or do things to. Look through your current program also, at the variables you used.
Some of the the “nouns” won’t be interesting, but others will represent things that are really important to your program - focus on just the 1-3 most important. Look for things that are made up of smaller pieces. Simple classes are often made from just “part to whole” relationships (also called “composition”). By storing related pieces of data together you can treat them as one big… object. It’s one way of making a program easier to think about when it starts to get big. Instead of having to think about many many small pieces of data, we group them together and think about the group as one whole.
After deciding what data might go together, you can look at your classes and think about useful operations you want to be able to do with each kind of data. That’s how you start to decide what should be a method. It’s very subjective but often you can find functions that are closely associated with a particular class, and those are easy candidates to turn into methods.
Later on you’ll find classes used in other ways as well - the things they represent can be very abstract, and they can be combined in some interesting ways. But the basics are always compound data + operations on the data.
Hey Joseph… so yeah classes can be tricky and pretty subjective just as @flyinghyrax has uttered. One way to know classes is to think about a blue print or a plan to create something or an item. Whenever you want to convert functions think of methods. once you define a function inside a class it becomes a method. Now methods and functions r used interchangeably. If you’ve been curious to check whenever you put a period after a package name/library module you’ll often see some associated data highlighted with the library, so those are the functions/methods that you can call or use. e.g. time.sleep
Let me try and put it this way, like lets say we have a item car and we want to produce many cars that function just like the original car we made initially. we know that a car has to move, stop, horn, play music etc. These are all the methods(functions) associated with cars. So its much easier then to create a class(blue print) to increate instances of that car with the same functionality something like…
class Car:
def drive():
print('moving')
def stop():
print('stopping')
car1 = Car()
car1.drive()
# you can add other methods
# car1 just place a period to see methods associated with it
Let’s go back to our task at hand we are creating new files from our various functions, save, preview, address_input, the main… these become methods once we define in a class. such that if you say new_file = create_NewFile(). Then new_File will have all the associated methods you can preview, save but here it only make sense for main since preview cant work without adding addresses.
In a gist for you to create a class you need a constructor to specify the requirements needed to create an instance or prototype out of that class… I’ve indicated more in the code. The self key word is like a place holder for the instances that we have created instead of repeating the car or newFile everywhere… so when you see self just know that is newFile as I’ve indicated. Am brushing through so finally the if __name__ == '__main__': just tells the program before it runs these are the rules to follow… if this is the current file that is running directly kinda hard to explain… beware that this main is not the main function that we defined as a function… find a way to understand it more easily… nywy here is the code… I’ve just added a way to get the file name with its extension and to prompt the user to cross check if the file is okay before saving it… cheers
'''
creating new files
'''
# know that a class is a blue print to create objects or further instances of a thing or item
# functions are called methods once defined in a class
class create_NewFile:
def __init__(self) -> None:
# what do we require to create our new file?(essentially the requirements of our constructor)
self.label_line1 = ""
self.new_file_name = ""
# declare and initilaize the labels remaining the balel 1 and 2
def save_file(self):
while True:
try:
self.file_name = input("Please type the name of your new file?.")
self.extension_of_file = input("Please enter the extension type of your new file.")
self.new_file = self.file_name + '.' + self.extension_of_file
return self.new_file
except Exception as e:
print("An error has occured.")
print("Please try again.")
return None
def address_input(self):
while True:
try:
fn = input("Your first name: ")
mi = input("Your middle name/initial: ")
ln = input("Your last name: ")
phone_num = input("Your Phone number: ")
# left this portion so that you can add the other labels and try it out
self.label_line1 = f"{fn} {mi} {ln} - {phone_num}\n"
return self.label_line1
break
except Exception as e:
print("Information not collected, please try again")
return None
def write_file(self):
while True:
try:
with open(self.new_file, 'w') as file:
file.write(self.label_line1)
# add the rest of the fields
print(f" {self.new_file} was written succesfully.")
break
except FileNotFoundError as e:
print(f"File not found: {e}")
except IOError as e:
print(f"An error has occured, file not written. Please try again")
def preview(self):
print("Your address label preview: ")
print(str(self.label_line1))
# add the rest of the fields
def main(self):
while True:
self.new_file_name = self.save_file()
if self.new_file_name is not None:
self.label_line1 = self.address_input()
self.preview() # to prompt the user if the file is okay to save
confirmation = input("Do you want to proceed with saving? (yes/no)").strip().lower()
if confirmation == 'yes':
self.write_file()
elif confirmation == 'no':
print('not saved')
break
else:
print('not applicable')
break
# if we are executing this program directly then carry out the stated instructions
if __name__ == '__main__':
new_File = create_NewFile() # we are just creating an instance of a new file from our blue print
new_File.main() # then we call the method to create our new file