【问题标题】:Problems with python class inheritance [duplicate]python类继承问题[重复]
【发布时间】:2016-07-24 03:35:51
【问题描述】:

我正在玩 python 类继承,但我似乎无法让子类工作。

我在这里得到的错误信息是:

must be a type not classobj

代码如下:

class User():
    """Creates a user class and stores info"""
    def __init__(self, first_name, last_name, age, nickname):
        self.name = first_name
        self.surname = last_name
        self.age = age
        self.nickname = nickname
        self.login_attempts = 0

    def describe_user(self):
        print("The users name is " + self.name.title() + " " + self.surname.title() + "!")
        print("He is " + str(self.age) + " year's old!")
        print("He uses the name " + self.nickname.title() + "!")

    def greet_user(self):
        print("Hello " + self.nickname.title() + "!")

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0

class Admin(User):
    """This is just a specific user"""
    def __init__(self, first_name, last_name, age, nickname):
        """Initialize the atributes of a parent class"""
        super(Admin, self).__init__(first_name, last_name, age, nickname)

jack = Admin('Jack', 'Sparrow', 35, 'captain js')
jack.describe_user()

我使用的是 Python 2.7

【问题讨论】:

标签: python class inheritance python-2.x


【解决方案1】:

User 类必须继承自 object,如果您稍后要调用 super()

class User(object):

...

Python2 区分了不继承自 object 的旧样式类和继承自 object 的新样式类。最好在现代代码中使用新样式的类,而将它们混合在继承层次结构中是不好的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-30
    • 2016-07-19
    • 1970-01-01
    • 2012-08-08
    • 2021-05-08
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多