Python子类的属性少于父类

时间:2019-09-08 02:42:02

标签: python

我有点困惑。在两个不同的脚本中,我创建了一个子类,该子类的属性少于其父类。由于某种原因,在一种情况下,代码可以正常工作,而在另一方面,由于缺少位置参数,我经常遇到TypeErrors。

此代码可以正常运行:

class Restaurant:
    def __init__(self, restaurant_name, cuisine_type):
        self.name = restaurant_name
        self.cuisine = cuisine_type
        self.number_served = 0

--SNIP--

class IceCreamStand(Restaurant):
    def __init__(self, restaurant_name):
        super().__init__(self,restaurant_name)
        self.name = restaurant_name

但是,这看起来与我相同,但在第super().__init__(self, first_name)行中对于某些人来说一直失败,说 init 缺少2个附加的位置参数。

class User:
    def __init__(self, first_name, last_name, location, occupation):
        self.name = first_name
        self.surname = last_name
        self.location = location
        self.job = occupation
        self.login_attempts = 0

--SNIP--

class Privileges(User):
    def __init__(self, first_name):
        super().__init__(self, first_name)
        self.name = first_name
        self.privileges_admin = ('can add posts'
                           , "can edit other users' posts", 'can delete posts',
                           'can modify posts', 'can ban users')
        self.privileges_user = ('can add posts', 'can edit own posts')

任何人都可以解释为什么会发生这种情况吗?

2 个答案:

答案 0 :(得分:3)

使用super()。func()

我认为这意味着您调用了父方法。

意味着您应该在父方法中传递相同的参数。

class User:
    def __init__(self, first_name, last_name, location, occupation):

赞:

class Privileges(User):
    def __init__(self, first_name):
        super().__init__(first_name, 'default', 'default', 'default')

或者:

class Privileges(User):
    def __init__(self, first_name, last_name, location, occupation):
        super().__init__(first_name, last_name, location, occupation)

我英语不是很好。希望对您有帮助

答案 1 :(得分:1)

您以错误的方式使用super().__init__()-您必须在没有self的情况下运行它。

Restaurant.__init__()期望两个值restaurant_name, cuisine_type(不是三个),并且在IceCreamStand.__init__()中使用super().__init__()将两个值Restaurant.__init__()和{发送到self {1}}-但是它们的分配方式与您期望的不同

restaurant_name

如果在restaurant = self cuisine_type = restaurant_name 中添加

Restaurant.__init__()

然后您会看到自己的错误。


print(restaurant_name, cuisine_type) 期望有4个值,而不是5-User.__init__()。在使用first_name, last_name, location, occupation的{​​{1}}中,您将2个值发送到Privileges.__init__(),但它又需要2个值,并且您会收到错误消息super().__init__()