AttributeError:'User'对象无'show_privileges'属性问题排查
解决AttributeError: 'User'对象没有'show_privileges'属性的问题
核心问题一目了然:你创建管理员对象时用了User类,而非自己定义的Admin子类。
Python中,对象能调用的方法完全由它所属的类决定。你确实在Admin类里实现了show_privileges方法,但admin = User("Fred", ...)这行代码创建的是User类的实例——User类本身根本没有这个方法,所以调用admin.show_privileges()时必然报错。哪怕你手动给这个User实例添加了privileges属性,也没法让它拥有Admin类独有的方法。
只需要修改一行代码,把实例化对象的类改成Admin即可:
class User: def __init__(self, first_name, last_name, login_attempts, email, location): self.first_name = first_name self.last_name = last_name self.login_attempts = login_attempts self.email = email self.location = location def describe_user(self): print(f"{self.first_name} {self.last_name}") print(f"You have {self.login_attempts} login attempts") print(f"{self.email}") print(f"{self.location}") def greet_user(self): print(f"Hi {self.first_name} {self.last_name} ") def location_user(self): print(f"Hi {self.first_name},you are from London, South") def increment_login_attempts(self, login): self.login_attempts = + login class Admin(User): def __init__(self, first_name, last_name, login_attempts, email, location): super().__init__(first_name, last_name, login_attempts, email, location) self.privileges = [] def show_privileges(self): print("\nPrivileges:") for privilege in self.privileges: print(f"- {privilege}") # 将User改为Admin,创建正确的子类实例 admin = Admin("Fred", "Osei", "6", "fred@fredas.com", "London") fred = User("John", "Chris", "8", "johnchris@life.com", "Manchester") admin.describe_user() admin.privileges = ["Can Post", "Can Create Accounts", "Can Delete Account"] admin.show_privileges()
另外顺便提一句:你代码里show_privileges方法中的变量名priviledge拼写错误,正确应为privilege,虽然不影响运行,但规范拼写能避免后续潜在的问题。
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

