编程错误1


访问属性时报错:AttributeError: ‘Admin’ object has no attribute ‘show_privilege’

class User:
    """创建一个与用户相关的类"""

    def __init__(self, first_name, last_name, 
                 username, email, location):
        """初始化各属性"""
        self.first_name = first_name
        self.last_name = last_name
        self.username = username
        self.email = email
        self.location = location

    def describe_user(self):
        """创建一个描述用户信息的函数"""
        print("{} {}'s username is {},
              his(her) emile is {},
              his(her) location is {}."
              .format(self.first_name.title(),
                      self.last_name.title(),
                      self.username,
                      self.email,
                      self.location.title()))

    def greet_user(self):
        """创建一个打招呼的函数"""
        print("Hello,{} {},
              next to meet you."
              .format(self.first_name, self.last_name))


class Admin(User):
    # 这个用户的独特之处
    def __init__(self, first_name, last_name, 
                 username, email, location):
        """重新定义这个特殊的用户"""
        super().__init__(first_name, last_name,
                        username, email, location)
        self.privileges = []

    # 展示这个用户的特殊信息
    def show_privileges(self):
        print("\nPrivileges:")
        for privilege in self.privileges:
            print("-" + privilege)


user = Admin("Chen", "Xili", "fire wolf", 
            "1239968427@qq.com", "yangxin")
user.describe_user()

user.privileges = ['can add post',
                   'can delete post',
                   'can ban user',
                   ]
user.show_privilege()

出现报错:

Traceback (most recent call last):
  File "F:/学习资料/python_work/Chapter9/9-7.py", line 49, in <module>
    user.show_privilege()
AttributeError: 'Admin' object has no attribute 'show_privilege'

经过排查发现是最后访问属性时user.priviliges()误打成了user.privilige()
修改后:

user.show_privileges()

成功输出:

Chen Xili's username is fire wolf,his(her) emile is 
1239968427@qq.com,his(her) location is Yangxin.

Privileges:
-can add post
-can delete post
-can ban user

Process finished with exit code 0

以后再写代码时要注意准确性,不要轻易敲错字母,特别是涉及函数文件的字母。


文章作者: 陈细利
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 陈细利 !
评论
 上一篇
Python基础语法1 Python基础语法1
参考教材:Python程序设计基础与应用(机械工业出版社/董付国) ​ 本复习资料中语法出现顺序与参考教材保持一致,为巩固记忆,全程手打,没有复制粘贴。(因此可能会出现错别字请见谅) 由于内容过多,将逐步发布。 第一章1.标准
本篇 
编程错误1 编程错误1
访问属性时报错:AttributeError: ‘Admin’ object has no attribute ‘show_privilege’ class User: """创建一个与用户相关的类""" def __in
2020-07-12
  目录