使用__init__继承属性 [英] The inheritance of attributes using __init__
问题描述
我是刚刚开始学习Python的Java人。举个例子:
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
我确定有很多冗余代码(我知道在Java中,上面的代码有很多冗余)。
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?
推荐答案
在python中为类编写 __ init __
函数时,你应始终调用其超类的 __ init __
函数。我们可以使用它将相关属性直接传递给超类,因此您的代码如下所示:
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)
super(Teenager, self).__init__(name, phone)
并且代码将执行相同的操作。这是因为在python instance.method(args)
只是 Class.method(instance,args)
的简写。如果你想使用 super
,你需要确保指定 object
作为人
就像我在我的代码中所做的那样。
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.
python文档提供了有关如何使用 super
关键字的更多信息。在这种情况下,重要的是它告诉python在 self
的超类中查找方法 __ init __
不是青少年
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屋!