Search code examples
pythonsuper

Can I call super in a loop in python?


How can I make the following code work, and if it's not possible what better ways are there to do this particular thing? I can't seem to figure it out, since I believe I shouldn't create an object of the parent. Just writing super() doesn't seem to work here for me (3.6.5).

class Geometry(object):
    def __init__(self, **kwargs):
        if kwargs:
            allowed = ['lat', 'lng', ]
            for k,v in kwargs.items():
                if k in allowed:
                    setattr(self, k, v)

class Address(Geometry):
    def __init__(self, d = None):
        if d:
            for k,v in d.items():
                if k in Geometry:
                    setattr(super, k, v)
                if k in Allowed('Address'):
                    setattr(self, k, v)

I'm trying to push values up to the parent class, but without knowing the attribute names before they are in a list of allowed ones.

I know Geometry doesn't support membership testing as of this moment, because nothing is defined.

The Geometry superclass has the attributes lat, lng, name etc. The Allowed helper class will return a list of strings representing allowed keys for the Address class.


Solution

  • I'm sure that you are using super in the wrong way.

    You should initialise the super class first:

    class Geometry(object):
        def __init__(self, **kwargs):
            if kwargs:
                allowed = ['lat', 'lng', ]
                for k,v in kwargs.items():
                    if k in allowed:
                        setattr(self, k, v)
    
    class Address(Geometry):
        def __init__(self, **d = None):
            super().__init__(d)
            if d:
                for k,v in d.items():
                    if k in Allowed('Address'):
                        setattr(self, k, v)
    

    In this way, the super class sorts itself out.

    Your Address class can sort its own attributes out. (Helped by Allowed).

    I've assumed that the d param is a dictionary just like kwargs.

    The way you were using super meant to me that you should have just used self. (except that k in Geometry did not really mean anything)