Home > OS >  Why is it when I call an attribute of my class, it is printing an older variable instead of the late
Why is it when I call an attribute of my class, it is printing an older variable instead of the late

Time:03-24

I am working with Python class and methods at the moment, and I have the following code:

class Employee:
    def __init__(self, first,last):
        self.first = first
        self.last = last
        self.email = first   '.'   last   "@gmail.com"

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


emp_1 = Employee('John','Smith')
empl_1.first = 'Patrick'

print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())

And the output is:

Patrick
[email protected]
Patrick Smith

What I am struggling to understand is that when I print the first name by itself, and the full name of the employee, it is using the latest first name, which is defined to be 'Patrick'. However, for the email function, it is still using 'John'. Can someone kindly explain why this is the case?

CodePudding user response:

You only define self.email once - when initialising the object. It will not magically update whenever you change other variables.

  • Related