从Super继承Python类args

时间:2012-12-11 06:38:37

标签: python class inheritance

我想从collection类继承Base arg。怎么样?

class Base(object):
    def __init__(self, collection=None, classname=None):
        self.__collection__ = collection or self.__class__.__name__

class Thing(Base):
    def __init__(self, **kwargs):
        super(Thing, self).__init__()
        self.__dict__.update(kwargs)


t = Thing(collection='foobar')
t.__collection__

>>> 'Thing'

:(

4 个答案:

答案 0 :(得分:1)

我通常不会使用super()。我改为直接调用__init__函数。类似的东西:

class Base(object):
    def __init__(self, collection=None, classname=None):
        self.__collection__ = collection or self.__class__.__name__

class Thing(Base):
    def __init__(self, **kwargs):
        #super(Thing, self).__init__()
        Base.__init__(self, **kwargs)
        #self.__dict__.update(kwargs)


t = Thing(collection='foobar')
print(t.__collection__)

应该得到你想要的东西。

答案 1 :(得分:0)

不要在实例变量的开头使用双下划线,并避免在开头和结尾使用它们,因为双下划线在python中有特殊含义。

如果实例变量的标识符以双下划线开头,则“名称损坏”以避免子类名称空间中的冲突,因此self.__collections实际上变为self._Base__collections。 实例变量标识符的开头和结尾的双下划线保留用于特殊方法和特殊名称(例如__add____class__)。

实例变量应以字母(例如collections)或单个下划线开头,表示它们是私有的(例如_collections

无论如何,在您的示例中,您设置的collection属性不存在。如果您在self.collection类中命名了属性Base,它将正常工作。

说清楚:

>>> class Base(object):
...     def __init__(self, collection=None):
...             self.__collection__ = collection or self.__class__.__name__
... 
>>> class Thing(Base):
...     def __init__(self, **kwargs):
...             super(Thing, self).__init__()
...             self.__dict__.update(kwargs)
... 
>>> t = Thing(collection=3)   __dict__.update creates a new instance attribute
>>> t.__collection__
'Thing'
>>> t.collection   # here it is
3
>>> t = Thing(**{'__collection__': 7})   #UGLY! Do not do this!!!
>>> t.__collection__
7

答案 2 :(得分:0)

您只需将kwargs“转发”到您的基类__init__()方法:

class Thing(Base):
    def __init__(self, **kwargs):
        super(Thing, self).__init__(**kwargs)
        self.__dict__.update(kwargs)

t = Thing(collection='foobar')
assert t.__collection__ == 'foobar'
assert t.__dict__.get('collection') == 'foobar'

您只是使用默认参数调用Base.__init__()

答案 3 :(得分:0)

您在寻找super(Thing, self).__init__(**kwargs)吗?这会将关键字参数传递给超类__init__

相关问题