Classes
This code snippet comes from Heath Adams at TCM Security, and is the best snippet i have been able to find to understand Python classes. I have also added comments to help you understand the flow.
#Defining your class
class Shoes:
#Initiates the class and assigns the `name` and `price` values
def __init__(self, name, price):
self.name = name
self.price = float(price)
#Checks the input of the user to make sure that the input is an integer or a float
def budget_check(self, budget):
if not isinstance(budget, (int, float)):
print('Invalid entry. Please enter a number.')
exit()
#Calculates the change from your budget based on the inputted price
def change(self, budget):
return (budget - self.price)
#Calculates whether or not you'll be able to afford the shoes and uses the above class functions to compile the data
def buy(self, budget):
self.budget_check(budget)
if budget >= self.price:
print(f'You can cop some {self.name}')
if budget == self.price:
print('You have exactly enough money for these shoes.')
else:
print(f'You can buy these shoes and have ${self.change(budget)} left over')
exit('Thanks for using our shoe budget app!')Last updated