类在结果后返回None

时间:2020-11-11 02:11:34

标签: python class subclass

我有一个正在尝试处理的类User和一个子类Admin,但是当我尝试调用它们的一个实例时,在返回结果后,我一直不返回任何内容

class User:
    def __init__(self, first_name, last_name, age, height):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.height = height

    def describe_user(self):
        print(f"{self.first_name} {self.last_name}\n{self.age} " \
            f"years old\n{self.height} cm tall")

    def greet_user(self):
        print(f"Hi, {self.first_name} {self.last_name}! ")


class Admin(User):
    def __init__(self, first_name, last_name, age, height):
        super().__init__(first_name, last_name, age, height)
        self.privileges = ['post', 'delete post', 'ban user']
        
    def show_privileges(self):
        print(f"{self.first_name} can:")
        for item in self.privileges:
            print(item)
    
person = Admin('John', 'Doe', 20, 180)
print(person.describe_user())
print(person.show_privileges())


John Doe
20 years old
180 cm tall
None
John can:
post
delete post
ban user
None

我正在尝试找出这种情况的发生原因以及解决方法

2 个答案:

答案 0 :(得分:2)

person.describe_user()隐式返回None,因为它在函数体内没有return语句(仅打印值)。这将导致print(person.describe_user())打印None

解决方案是只写person.describe_user(),不写多余的print(),下一行类似。

答案 1 :(得分:0)

describe_usershow_privileges做自己的print处理;它们没有返回值,因此它们隐式返回None。摆脱对它们每个人的调用周围的print,使代码的结尾恰好:

person = Admin('John', 'Doe', 20, 180)
person.describe_user()
person.show_privileges()

,您将不会打印出它们无用的返回值(None)。