Reputation: 7505
I've been reading through some code and came across something that makes me think I understand super
less well than I thought I did. What I saw was:
class Model(object):
'''Abstract base model class.
'''
...
def get_config(self, verbose=0):
'''Return the configuration of the model
as a dictionary.
To load a model from its configuration, use
`keras.models.model_from_config(config, custom_objects={})`.
'''
config = super(Model, self).get_config()
Now, the Model
class only inherits from object
, so why is there a super
? Does the object
class have a get_config
method ? (Not that I can see). Is this some sort of defensive programming technique, in case a class comes between object
and Model
? If so, how often & why does that sort of thing happen? If not, is there some other reason for this super
?
Upvotes: 0
Views: 539
Reputation: 4681
object
does not have a valid instance method get_config()
so this code, specifically, should not work. However, super essentially takes the parent class of a derived class. This is Python2 syntax. In Python3, you can simply call super()
with no parameters.
Anyways, here's an example:
class Number(int):
def __eq__(self, other):
equal = super(Number, self).__eq__(other)
print("{} and {} are {}equal".format(self, other, "not " if not equal else ""))
return equal
def __str__(self):
return "Number({})".format(super(Number, self).__str__())
i = Number(5)
j = Number(7)
print(i == j) # Output:
"""
Number(5) and Number(7) are not equal
False
"""
This inherits from int
and will modify the instance methods of int, while still being able to use the original methods.
In order for this code to work, you could overload the object
class (I do not recommend this...).
class object(object):
def __init__(self):
pass
def get_config(self):
print("Getting object Config")
return "config"
class Foo(object):
def __init__(self):
self.config = None
def get_config(self):
self.config = super(Foo, self).get_config()
print("Getting Foo Config")
i = Foo()
i.get_config()
print(i.config)
Upvotes: 1