使用 __init__ 继承属性 [英] The inheritance of attributes using __init__

查看:43
本文介绍了使用 __init__ 继承属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是刚开始学习 Python 的 Java 人.举个例子:

class Person():def __init__(self, name, phone):self.name = 姓名self.phone = 电话班级青少年(人):def __init__(self, name, phone, website):self.name=nameself.phone=电话self.website=网站

我确定有很多冗余代码(我知道在 Java 中,上面的代码有很多冗余).

关于哪些属性已经从父类继承,哪些部分是多余的?

解决方案

在 Python 中为类编写 __init__ 函数时,应始终调用其的 __init__ 函数它的超类.我们可以使用它来将相关属性直接传递给超类,因此您的代码将如下所示:

class Person(object):def __init__(self, name, phone):self.name = 姓名self.phone = 电话班级青少年(人):def __init__(self, name, phone, website):Person.__init__(self, name, phone)self.website=网站

正如其他人指出的那样,您可以替换该行

Person.__init__(self, name, phone)

super(Teenager, self).__init__(name, phone)

并且代码会做同样的事情.这是因为在 python 中 instance.method(args) 只是 Class.method(instance, args) 的简写.如果您想使用 super,您需要确保将 object 指定为 Person 的基类,就像我在代码中所做的那样.

python 文档 提供了有关如何使用 的更多信息super 关键字.在这种情况下,重要的是它告诉 python 在不是 Teenager

self 的超类中查找方法 __init__>

I'm Java person who just started learning Python. Take this example:

class Person():
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone

class Teenager(Person):
    def __init__(self, name, phone, website):
        self.name=name
        self.phone=phone
        self.website=website

I'm sure there's a lot of redundant code (I know in Java, there are a lot of redundancies for the bit of code above).

Which parts are redundant with respect to which attributes are already inherited from the parent class?

解决方案

When writing the __init__ function for a class in python, you should always call the __init__ function of its superclass. We can use this to pass the relevant attributes directly to the superclass, so your code would look like this:

class Person(object):
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone
class Teenager(Person):
    def __init__(self, name, phone, website):
        Person.__init__(self, name, phone)
        self.website=website

As others have pointed out, you could replace the line

Person.__init__(self, name, phone)

with

super(Teenager, self).__init__(name, phone)

and the code will do the same thing. This is because in python instance.method(args) is just shorthand for Class.method(instance, args). If you want use super you need to make sure that you specify object as the base class for Person as I have done in my code.

The python documentation has more information about how to use the super keyword. The important thing in this case is that it tells python to look for the method __init__ in a superclass of self that is not Teenager

这篇关于使用 __init__ 继承属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆