Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

python - The inheritance of attributes using __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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...