class User:
"""模拟用户的一些参数"""
def __init__(self,first_name,last_name,occupation):
"""初始化属性first_name,last_name和occupation"""
self.first_name = first_name
self.last_name = last_name
self.occupation = occupation
def describe_user(self):
print(self.first_name,self.last_name,self.occupation)
def greet_user(self):
print(f"Hello,{self.first_name} {self.last_name}!")
"""9.8编写一个Privileges的类,引用9.7中的内容"""
class Privileges():
def __int__(self):
self.privileges=['can add post','can delete post','can ban user']
def show_privileges(self):
print(f"The admin's privileges are {self.privileges}")
"""编写一个继承User类的名为Admin的子类"""
class Admin(User):
def __init__(self,first_name,last_name,occupation):
super().__init__(first_name,last_name,occupation)
self.privileges=Privileges()
lee = Admin('biee','lee','Engineer')
lee.describe_user()
lee.greet_user()
lee.privileges.show_privileges()
错误信息:
biee lee Engineer
Hello,biee lee!
Traceback (most recent call last):
File "C:\Users\Lee\Desktop\python_work\Chapter 9\privileges.py", line 36, in <module>
lee.privileges.show_privileges()
File "C:\Users\Lee\Desktop\python_work\Chapter 9\privileges.py", line 23, in show_privileges
print(f"The admin's privileges are {self.privileges}")
AttributeError: 'Privileges' object has no attribute 'privileges'
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "C:\Users\Lee\Desktop\python_work\Chapter 9\privileges.py"]
[dir: C:\Users\Lee\Desktop\python_work\Chapter 9]
[path: C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%SYSTEMROOT%\System32\OpenSSH\;C:\Users\Lee\AppData\Local\Programs\Python\Python310\Scripts\;C:\Users\Lee\AppData\Local\Programs\Python\Python310\;C:\Users\Lee\AppData\Local\Microsoft\WindowsApps;]
请问错在哪里,查了好久。
__int__
第20行单词拼错了
应该是
__init__
20行的默认构造函数错了,是__init__(self):
第20行的’int‘改为‘init’
你的class Privileges()类里没有定义privileges()这个方法。是不是代码少了?
运行如下:
class User:
"""模拟用户的一些参数"""
def __init__(self, first_name, last_name, occupation):
"""初始化属性first_name,last_name和occupation"""
self.first_name = first_name
self.last_name = last_name
self.occupation = occupation
def describe_user(self):
print(self.first_name, self.last_name, self.occupation)
def greet_user(self):
print(f"Hello,{self.first_name} {self.last_name}!")
"""9.8编写一个Privileges的类,引用9.7中的内容"""
class Privileges():
def __init__(self):
self.privileges = ['can add post', 'can delete post', 'can ban user']
def show_privileges(self):
print(f"The admin's privileges are {self.privileges}")
"""编写一个继承User类的名为Admin的子类"""
class Admin(User):
def __init__(self, first_name, last_name, occupation):
super().__init__(first_name, last_name, occupation)
self.privileges = Privileges()
lee = Admin('biee', 'lee', 'Engineer')
lee.describe_user()
lee.greet_user()
lee.privileges.show_privileges()