Python中Admin对象报错无'privileges'属性,请求技术支持
问题排查与解决
错误根源是Admin类的构造函数名称拼写错误:你把Python要求的构造函数__init__写成了__ini__(少了最后一个t)。
Python只会自动调用类中名为__init__的方法作为构造函数,拼写错误的__ini__会被当成普通方法,实例化Admin对象时根本不会执行,导致self.privileges属性从未被初始化,调用describe_privileges时自然会抛出"AttributeError: 'Admin' object has no attribute 'privileges'"。
修正后的代码如下:
class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.login_attempts = 0 def describe_user (self): full_name = f"{self.first_name.title()} {self.last_name.title()}" return full_name def greet_user (self): print(f"welcome to West World, {self.first_name.title()}") def increment_login_attempts (self, attempts): """increments login attempts by 1""" self.login_attempts += attempts print(f'{self.login_attempts}') def reset_login_attempts (self): self.login_attempts = 0 print(f'{self.login_attempts}') class Admin (User): def __init__ (self, first_name, last_name): # 修正拼写错误 super().__init__(first_name, last_name) self.privileges = ['registrar authorization','content moderation','ad management'] def describe_privileges (self): print('Admin has the following privileges:') for privilege in self.privileges: print(f'\t{privilege.title()}') admin = Admin ('deloris','ferland') print(admin.describe_user()) admin.greet_user() admin.increment_login_attempts(1) admin.describe_privileges()
内容的提问来源于stack exchange,提问作者user20422642
相关产品推荐
相关产品推荐

