Search code examples
pythonpython-3.xpython-object

Positional arguments and the self keyword


class Employee:

    def __init__(self, first, last):
        self.first = first
        self.last = last

    def fullname():
        return '{} {}'.format(self.first, self.last)

emp = Employee('Rob', 'M')

print (emp.fullname())

You will notice I left out the self keyword in the fullname method, so I get:

TypeError: fullname() takes 0 positional arguments but 1 was given

Is this actually an arguments error? My guess was no so I tried:

class Employee:

    def __init__(foo, first, last):
        foo.first = first
        foo.last = last

    def fullname():
        return '{} {}'.format(self.first, self.last)

emp = Employee('rob', 'm')

print(emp.fullname())

and a few other things such as leaving self out of the return statement in fullname(). However, each method of alteration says the error is a TypeError. So I am stumped, why is fullname() being passed an argument?


Solution

  • Consider the following:

    def fullname():
        return '{} {}'.format(self.first, self.last)
    

    In the preceding method, what does the variable self refer to in self.first? How does Python know what you mean when you type self?

    All methods are implicitly passed their parent object as their first parameter, just like sys.argv[0] is always the script name. This is so things like self.first can work.