SUPERBUG_JUN 2022-03-11 11:33 采纳率: 100%
浏览 43
已结题

python问题?第二个类定义了privileges_list属性,为什么还会报错?

python问题?第二个类定义了privileges_list属性,为什么还会报错?
问题相关代码,请勿粘贴截图
class User:
    def __init__(self,first_name,last_name,login_attempts):
        self.first_name = first_name
        self.last_name = last_name
        self.login_attempts = login_attempts
    def describe_user(self):
        name = self.first_name+self.last_name
        print(name)
    def greet_user(self):
        print('Hello',self.first_name,'.',self.last_name)
    def increment_login_attempts(self):
        for i in range(1,10,2):
            self.login_attempts =int(self.login_attempts) +i
            print(self.login_attempts)
    def reset_login_attempts(self):
        self.login_attempts =0
        print(f"重置后:{self.login_attempts}")
class Privileges:
    def _init_(self,privileges_list = ['can add post','can delete post','can ban user']):
        self.privileges_list = privileges_list
    def show_privileges(self):
        print(f"your privileges as follows:{self.privileges_list}.")

class Admin(User):
    def __init__(self,first_name,last_name,login_attempts):
        super().__init__(first_name,last_name,login_attempts)
        self.privileges = Privileges()  # 将实例用作属性

user = Admin(first_name='zhang',last_name='samsam',login_attempts=10)
user.describe_user()
user.greet_user()
user.privileges.show_privileges()#user先调用Admin中priviles属性再调用show_privieges方法
user.increment_login_attempts()
user.reset_login_attempts()
运行结果及报错内容

D:\Anacoda\pythonw.exe D:/pycharm/pythonProject/main.py
zhangsamsam
Hello zhang . samsam
Traceback (most recent call last):
File "D:/pycharm/pythonProject/main.py", line 32, in
user.privileges.show_privileges()#user先调用Admin中priviles属性再调用show_privieges方法
File "D:/pycharm/pythonProject/main.py", line 22, in show_privileges
print(f"your privileges as follows:{self.privileges_list}.")
AttributeError: 'Privileges' object has no attribute 'privileges_list'

我的解答思路和尝试过的方法
我想要达到的结果
  • 写回答

3条回答 默认 最新

  • 谛凌 2022-03-11 11:49
    关注

    你少写了下划线,所以认为你没有定义这个变量

    class Privileges:
        #左右各两个下划线
        def __init__(self,privileges_list = ['can add post','can delete post','can ban user']):
            self.privileges_list = privileges_list
        def show_privileges(self):
            print(f"your privileges as follows:{self.privileges_list}.")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月19日
  • 已采纳回答 3月11日
  • 创建了问题 3月11日

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行