I am writing a code to document an employee system, the class can print full name, email:
class Employee:
def __init__(self,first,last):
self.first=first
self.last=last
def fullname(self):
print('{} {}'.format(self.first,self.last))
def email(self):
print('{}.{}@email.com'.format(self.first,self.last))
emp_1=Employee('John','Smith')
emp_1.first='Jim'
print(emp_1.first)
print(emp_1.email())
print(emp_1.fullname())
Output is like this:
I don't understand why when I call methods (email()
, fullname()
), I have a None
within the output?
The output is:
Jim
[email protected]
None
Jim
Smith
None
CodePudding user response:
You are using the method call inside a print
function. So it will try to print the value which is returned from the method. Since you are not returning anything from the method, it prints None
.
You can always return the value instead of printing them inside. Example.
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
def fullname(self):
# just printing the name will not return the value.
return '{} {}'.format(self.first, self.last)
def email(self):
# same, use a return statement to return the value.
return '{}.{}@email.com'.format(self.first, self.last)
emp_1 = Employee('John', 'Smith')
emp_1.first = 'Jim'
print(emp_1.first)
print(emp_1.email()) # print what is returned by the method.
print(emp_1.fullname())
It will give a proper output like
Jim
[email protected]
Jim Smith