lingcooo 2021-12-26 16:08 采纳率: 90.9%
浏览 192
已结题

python子类输出时怎么去掉none ?

子类继承父类后输出老是有None返回,不知道怎么去掉,望指点。


# 9-7: 创建Admin类,继承9-5类;添加privileges属性,存储由字符串组成的列表;添加show_privileges()方法,显示管理员权限;创建实例验证。
class User(): 
  def __init__(self, first_name, last_name): 
    self.first_name = first_name
    self.last_name = last_name
    self.sex = 'man'
    self.tall = ''
    self.login_attempts = 0
  
  
  def increment_login_attempts(self): 
    self.login_attempts += 1
  
  
  def reset_login_attempts(self): 
    self.login_attempts = 0  # 
  
  
  def describe_user(self):
    if self.tall: 
      man = f'first_name: {self.first_name.title()} last_name: {self.last_name.title()} Sex: {self.sex.title()} Tall: {self.tall.upper()}'
      print(man)
    else: 
      woman = f'first_name: {self.first_name.title()}last_name: {self.last_name.title()}Sex: {self.sex.title()}'
      print(woman)
      
  def greet_user(self): 
    if self.sex == 'man': 
      print(f'Hello Mr. {self.first_name.title()} {self.last_name.title()}.\n\t Welcom to the python.')
    else: 
      print(f'Hello Mis. {self.first_name.title()} {self.last_name.title()}.\n\t Welcom to the python.')
      
"""创建新类,继承上类"""
class Admin(User): 
  """管理员权限说明"""
  def __init__(self, first_name, last_name): 
    """初始化父类属性"""
    super().__init__(first_name, last_name)
    self.privileges = []
    
    
  def show_privileges(self): 
    show = f'{self.greet_user()}\n\t You have {self.privileges}.'
    print(show)
a = Admin('liu', 'rui')
a.sex = 'woman'
a.privileges = ['can Add post', 'can delete post', 'can ban user']
a.show_privileges()

输出显示为


Hello Mis. Liu Rui.
     Welcom to the python.
None
     You have ['can Add post', 'can delete post', 'can ban user'].

不会去掉这个None。

  • 写回答

1条回答 默认 最新

  • Hann Yang 全栈领域优质创作者 2021-12-26 17:13
    关注

    这个None是greet_user(self):方法用的print()的返回值,改成return 就没了None

      def greet_user(self): 
        if self.sex == 'man': 
          return(f'Hello Mr. {self.first_name.title()} {self.last_name.title()}.\n\t Welcom to the python.')
        else: 
          return(f'Hello Mis. {self.first_name.title()} {self.last_name.title()}.\n\t Welcom to the python.')
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 1月3日
  • 已采纳回答 12月26日
  • 创建了问题 12月26日

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效