Class basic questions


#1



https://www.codecademy.com/en/courses/python-intermediate-en-WL8e4/2/3?curriculum_id=4f89dab3d788890003000096

what the significance of ‘self.hours=hours'? since we did not use variable 'self.hours' why should we create this variable. Can we omit 'self.hours=hours', and directly return hours*20?


class Employee(object):
    """Models real-life employees!"""
    def __init__(self, employee_name):
        self.employee_name = employee_name

    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 20.00


#2

Yes you can.
self.hours is the pointing to the class property(Which means every employee object you create will have that property associated). In your case its fine since you are Saving the value of hours passed as argument to calculate_wage() in self.hours(which is an attribute/property on an Employee just like employee_name) run this code and see

class Employee(object):
	"""Models real-life employees!"""
	def __init__(self, employee_name):
		self.employee_name = employee_name
	def calculate_wage(self, hours):
		self.hours = hours
		return hours * 20.00
	def get_employee_hours(self):
		return self.hours
   		
jane = Employee("Jane Doe")
mike = Employee("Mike Doe")

print("%s earned $%s in %s hours"%(mike.employee_name,mike.calculate_wage(20),mike.hours))

#get the number of hours for this employee
print("Employee %s's hours are %s"%(mike.employee_name, mike.get_employee_hours()))#20

print()

print("%s earned $%s in %s hours"%(jane.employee_name,jane.calculate_wage(40),jane.hours))

#get the number of hours for this employee
print("Employee %s's hours are %s"%(jane.employee_name, jane.get_employee_hours()))#40

Now after running this snippet take out this line

self.hours = hours

and run the code again you will get an error saying

#AttributeError: 'Employee' object has no attribute 'hours'

Do you see the difference? Hope this helps


#3

Trying to digest, it is making sense to me. Thanks a lot :slight_smile: