Create a Python class called BasicClass
that just contains a static variable called theVariable
. Assign theVariable
a value of 1
.
class BasicClass():
theVariable = 1
Given the following ExampleClass
class, create an instance of the class and reference each of its attributes using the dot operator.
class ExampleClass:
age = 24
name = 'John Doe'
location = 'Toronto, Ontario'
##solution goes here
example_instance = ExampleClass()
print(example_instance.age)
print(example_instance.name)
print(example_instance.location)
24 John Doe Toronto, Ontario
Create a Python class called BirthdayBoy
that takes in two variables:
name
age
Do not forget your init
function!
Within BirthdayBoy
, create a method called birthday
that increases the value of age
by 1.
Once this class has been created, create an instance of the class then call the birthday
method on that class to increase its age. Check that the age has been appropriately increased by the birthday
method by referencing it using the dot operator (for example, instance.age
).
class BirthdayBoy:
def __init__(self, name, age):
self.name = name
self.age = age
def birthday(self):
self.age += 1
me = BirthdayBoy('nick', 24)
me.birthday()
me.age
25
Create a Python class called Salesperson
that has the following characteristics:
firstName
and lastName
that provide the salesperson's first and last names. (Don't forget about your init
function!)0
) called sales
that tracks the salesperson's sales over time.makeSale
that takes in an integer, and adds that integer to sales
.salesReport
that prints a string saying 'My total sales are {sales}!'
Once this is done, create a Salesperson
instance with firstName = 'Nick'
and lastName = 'McCullum
. Have the salesperson make a sale worth 500
and then run the salesReport
method.
This Salesperson
example is an excellent use case for the Class
structure in Python - you can have multiple
instances (salespeople) with the same characteristics and can track them separately.
class Salesperson:
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
sales = 0
def makeSale(self, saleValue):
self.sales += saleValue
def salesReport(self):
print(f'My total sales are {self.sales}!')
me = Salesperson('Nick','McCullum')
me.makeSale(600)
me.salesReport()
My total sales are 600!