0
class Employee:
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + "." + last + "@company.com"

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

So in fullname() you're supposed to only use self. I don't understand why I shouldn't have to write the first and last parameters.

quamrana
  • 37,849
  • 12
  • 53
  • 71

1 Answers1

2

This answer has a fairly detailed answer (and should explain the purpose of self) but to summarize:

Python uses the self argument (you can use any variable name instead, but it MUST be the first one in methods of a class and it MUST be remain identical in that class) to refer to the instance of the class the method is being called from and automatically passes that parameter for you whenever you call the method.

Thus, the self argument will have access to all the object's instance variables. In this case you declared self.first, self.last, self.pay, and self.email in your __init__ function which turned all of those variables into instance variables. That means that any method that gets called on that instance has access to them by calling self.<variable_name> just like you setup in the __init__.

Seyfi
  • 1,832
  • 1
  • 20
  • 35
MCBama
  • 1,432
  • 10
  • 18
  • That should be: "all of those variables into **instance** variables". – quamrana Dec 12 '17 at 20:16
  • @MCBama so any function I define inside that class has acess to the variables in the __init__ method? – Diogo Daniel Dec 12 '17 at 20:22
  • @DiogoDaniel Essentially. But you can actually define instance variables in any method at any time. As soon as you define a variable on `self` that variable becomes an instance variable. Which means if you had some function `def foo(self)` that declared `self.bar = True` and that method was called, you could access `self.bar` inside your `firstname(self)` function if you wanted. – MCBama Dec 12 '17 at 20:30
  • The reason you already have access to all the ones declared within the `__init__` function is because the init is the constructor and gets auto called whenever an instance is created. – MCBama Dec 12 '17 at 20:31
  • @DiogoDaniel Happy to help :). Hopefully cleared some stuff up for ya there. Good luck on the rest of your project! – MCBama Dec 12 '17 at 20:34