Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表打印问题_Python - Fatal编程技术网

Python 列表打印问题

Python 列表打印问题,python,Python,好的,我正在尝试制作一个代码来显示管理员权限列表。我让代码和东西正常工作,但它在任何列表项之前都给了我一个奇怪的显示: 输入代码: class Privileges: def __init__(*privileges): privileges def show_privileges(*privileges): print("these are your privileges:") for pri

好的,我正在尝试制作一个代码来显示管理员权限列表。我让代码和东西正常工作,但它在任何列表项之前都给了我一个奇怪的显示:

输入代码:

class Privileges:
    def __init__(*privileges):
        privileges
        
    def show_privileges(*privileges):
        print("these are your privileges:")
        for privilege in privileges:
            print(f"\t{privilege}")


class Admin(User):
    def __init__(self, first_name, last_name, age, username):
        super().__init__(first_name, last_name, age, username)
        self.privileges = Privileges()


Admin = Admin('Admin', '', '' ,'')
Admin.privileges.show_privileges('can add post', 'can delete post', 
    'can ban user')
输出:

 these are your privileges:
        <__main__.Privileges object at 0x7facd3c5f4f0>
        can add post
        can delete post
        can ban user
这些是您的特权:
可以添加帖子
可以删除帖子吗
可以禁止用户

函数
show_privileges(*privileges)
作为第一个参数被指定为
self
。这就是你看到的奇怪的输出,self正在打印。您需要在定义中包含self,如下所示:

def show_privileges(self, *privileges):
    print("these are your privileges:")
    for privilege in privileges:
        print(f"\t{privilege}")
或者,您可以对列表进行切片以避免第一个元素:

def show_privileges(*privileges):
    print("these are your privileges:")
    for privilege in privileges[1:]:
        print(f"\t{privilege}")
我认为第一种选择更为典型。

要阅读更多关于
self
及其在python中的工作原理的信息,可以阅读所提到的。

self
是作为方法调用它时的第一个参数。键入函数作为
def show_privileges(self,*privileges)
。最好不要对类和变量使用相同的名称
Admin=Admin(…)
您可以包含有关
self
参数的本教程链接: