如何正确传递super()中的扩充

时间:2014-08-01 19:44:40

标签: python python-2.7

我的课采取了一种称为资源的扩充:

> AClass(resource="123")

类别:

 class AClass(Base):
        def __init__(self, resource):
            super(AClass, self).__init__(self)

将在其扩展的Base类中设置。

class BaseHTTP(object):
    def __init__(self, resource, data=None):
        self.resource = resource

在Python 2.7中我应该做些什么来确保基类获取这些参数,这是好的......

super(Get, self).__init__(self, resource)

3 个答案:

答案 0 :(得分:5)

您不应将self传递给super(...).__init__,因为super(...).__init__会返回绑定的方法:

 class AClass(Base):
        def __init__(self, resource):
            super(AClass, self).__init__(resource)

另外,我不确定Get是什么。通常super的第一个参数应该是调用它的类 - 在本例中为AClass


奖金琐事:相比之下,super(...).__new__会返回 staticmethod ,因为__new__是一种静态方法。因此,对于__new__,仍必须传递self

super(...).__new__(self, ...)

答案 1 :(得分:1)

除了@ unutbu的优秀答案之外,我还要指出这个习语的规范用法。

class Parent(object):
    def __init__(self, name, species, gender):
        self.name = name
        self.color = color
        self.species = species
        self.gender = gender
        self.children = []
    def make_kid(self, partner, child_name):
        if self.gender == "F":
            return Child(mom=self, dad=partner, name=child_name,
                         species=self.species, gender=random.choice(["M", "F"]))
        else:
            return Child(mom=partner, dad=self, name=child_name,
                         species=self.species, gender=random.choice(["M", "F"]))

class Child(Parent):
    def __init__(self, mom=None, dad=None, *args, **kwargs):
        # a list of arguments we care about as a Child, followed by
        # *args, **kwargs that other classes further up the MRO may need
        self.mom = mom
        self.dad = dad
        # strip out the arguments we deal with here as a Child
        super(Child, self).__init__(*args, **kwargs)
        # then send the rest of them to the parent object

man = Parent("Adam","Human","M")
woman = Parent("Eve","Human","F")
child = man.make_kid(woman, "Junior")

答案 2 :(得分:0)

我通常使用:

class AClass(Base):
    def __init__(self, resource):
        Base.__init__(self, resource)

但我认为@unutbu解决方案更好。

希望这有帮助。