Putting self in arguments when creating classes


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

class PartTimeEmployee(Employee):
def init(self, name):
self.name = name
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
def full_time_wage(self, hours):
return super(PartTimeEmployee, self).calculate_wage(hours)
milton = PartTimeEmployee(“Brinley”)
print milton.full_time_wage(10)

What I noticed is that if in that code above, when I’m trying to override the calculate wage function that was defined earlier, if I put calculate_wage(self, hours) the code doesn’t work. Why is this? I thought that self was an argument for every function you define in a class.

tl;dr: When is self used in arguments when making classes and what is their significance?


Can’t run that, and difficult to guess what “doesn’t work” means - that really ought to be expressed in terms of what you expect and what you observed instead!

Without looking at the exercise itself, I have to note that it’s very strange for a method that’s supposed to calculate something, to also set an attribute on the object

While I don’t know what trouble you have with self, I can briefly explain how it’s used: Methods receive the object in question as their first argument, this binding happens when you obtain the method from the object (myobject.methodname). Perhaps you’re attempting to send it in twice ie. passing the object as an argument to a method that is already bound.

This behaviour is easily demonstrated:

mylist = []
appendmethod = mylist.append
appendmethod(1)  # note that mylist isn't passed to the method, the method is already aware of it
print mylist  # [1]

You could use the unbound version, and explicitly pass in the object:

mylist = []
unboundmethod = list.append  # note that it's obtained from the class, not the object
unboundmethod(mylist, 1)
print mylist  # [1]

This is usually not the right thing to do, but it can be useful when doing something fancy