I try to learn about classes in Python. Currently, I use the the tutorial from Corey Schafer.
Here is what he wrote:
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first "." last '@company.com'
emp_1 = Employee('First1', 'Last1', 50000)
emp_2 = Employee('First2', 'Last2', 60000)
print(emp_1.email)
print(emp_2.email)
My question is: Why he did not use self also here: self.email = self.first "." self.last '@company.com'
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = self.first "." self.last '@company.com'
emp_1 = Employee('First1', 'Last1', 50000)
emp_2 = Employee('First2', 'Last2', 60000)
print(emp_1.email)
print(emp_2.email)
The output is identical in the both ways.
CodePudding user response:
There is no difference if u use self.first
or first
inside the __init__
method since self.first
also points to the same variable, viz, first
.
Making a variable an attribute of self
just makes it an instance variable and allows u to access it anywhere inside your class