【问题标题】:__init__( ) missing 1 requirement positional argument__init__( ) 缺少 1 个要求位置参数
【发布时间】:2021-09-15 02:26:16
【问题描述】:

我想问一个与 Python 'class' 相关的问题,因为我在这个网站上练习练习 9.8 时遇到了这个例子: https://ehmatthes.github.io/pcc_2e/solutions/chapter_9/#9-9-battery-upgrade

示例编写一个单独的 Privileges 类。该类应该有一个属性,特权,它存储一个字符串列表,如练习 9-7 中所述。将 show_privileges() 方法移至此类。将 Privileges 实例作为 Admin 类中的属性。创建一个新的 Admin 实例并使用您的方法显示其权限。

#Seperate Privileges Class from Admin Class
#This is parent class
class User:
    def __init__(person, first_name, last_name, age, location, mail):
        person.first_name = first_name
        person.last_name = last_name
        person.age = age
        person.location = location
        person.mail = mail
        person.login_attempts = 0
    def describe_user(person):
        print(f"User full name: {person.first_name} {person.last_name}")
        print(f"User age: {person.age}")
        print(f"User location: {person.location}")
        print(f"User mail: {person.mail}")
    def greet_user(person):
        print(f"Hello {person.first_name} {person.last_name}!")
    def increment_login_attempts(person):
        person.login_attempts += 1
        
    def reset_login_attempts(person):
        person.login_attempts = 0
        
#This is child class Admin
class Admin(User):
    def __init__(self, first_name, last_name, age, location, mail): 
        super().__init__(first_name, last_name, age, location, mail)
        '''Initialize an empty set of privileges'''
        self.privileges = Privileges()    
#Seperate Privileges class: 
class Privileges:
    def __init__(self, privilege): (1)
        self.privileges = [] (2)
        
    def show_privileges(self):
        print("\nAdministrator's privileges are:")
        for privilege in self.privileges:
            print(f"- {privilege}")
    
Tom = Admin('Tom', 'Felton', 23, "the UK", 'tomfelton@hotmail.com')
Tom.describe_user()
Tom.privileges.privileges = ["can add post", "can delete post", "can ban user", "can do bla bla"]
Tom.privileges.show_privileges()

执行上面的整个代码后,我得到了这个错误:

我已经检查了上面同一个站点的答案,但是我很难理解为什么我应该将我的代码的第 (1) 行和第 (2) 行更改为这个:

def __init__(self, privileges=[]): (1)
        self.privileges = privileges  (2)

【问题讨论】:

  • def __init__(self, privilege) 声明该类在实例化期间需要一个参数:privilege。如果你不传递那个参数,你会得到一个错误。添加=[] 会为其提供默认值并使参数可选。
  • 谢谢@deceze

标签: python class init


【解决方案1】:

网站上给出的答案是错误的。

如果您想要一个可选的权限列表,您需要一个默认参数值。请注意,由于[] 是一个可变值,因此您需要使用类似None 的内容并将其替换为函数内的新空列表。

class Privileges:
    def __init__(self, privileges=None):
        self.privileges = [] if privileges is None else privileges

在签名中使用默认值[] 意味着使用默认值创建的每个Privileges 实例都将共享相同权限列表:对一个实例权限的更改将可见在其他人中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2021-06-05
    相关资源
    最近更新 更多