Py学习  »  Python

python类:当我调用类方法时,它总是在结果中输出一个“无”

Shawn11 • 3 年前 • 1151 次点击  

我正在写一个代码来记录一个员工系统,这个类可以打印全名,电子邮件:

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

我不明白为什么我调用方法( email() , fullname() ),我有一个 None 在输出范围内?

输出为:

Jim
Jim.Smith@email.com
None
Jim
Smith
None
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130932
 
1151 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Kris
Reply   •   1 楼
Kris    3 年前

您正在一个 print 作用因此,它将尝试打印该方法返回的值。因为你没有从这个方法返回任何东西,所以它会打印出来 None .

您总是可以返回值,而不是在内部打印它们。实例

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())

它将给出一个适当的输出,如

Jim
Jim.Smith@email.com
Jim Smith