简体   繁体   中英

inheritance — keyword and regular arguments in parent class

If I am doing this right, what is the right way to call an instance of ChildFoo? I ask this because I know that I'm supposed to place arguments before keyword arguments, but don't know what to do in this case...

class ParentFoo(object):
    def __init__(self,a,b,c=None):
        pass

class ChildFoo(ParentFoo):
    def __init__(self,d,e,f=None):
         ParentFoo.__init__(self, a, b, c = "fing")

Something like this?

class ParentFoo(object):
    def __init__(self,a,b,c=None):
        print(c)

class ChildFoo(ParentFoo):
    def __init__(self,d,e,f=None):
        super(ChildFoo,self).__init__(d,e,c="fing")

c = ChildFoo("1","2")

Official python doc here https://docs.python.org/2/library/functions.html#super

Since ChildFoo inherit from ParentFoo it must get argument also for the parent class

class ChildFoo(ParentFoo):
    def __init__(self, a, b, d, e, f=None):
         ParentFoo.__init__(self, a, b, c="fing")

I doesn't add 'c' - cause it seems that you want default value when ChildFoo init ParentFoo . Alternatively, you can supply default values to all the parent arguments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM