can someone explain 'super' to me?
Lie Ryan
lie.1296 at gmail.com
Sat Dec 5 06:10:28 EST 2009
On 12/5/2009 9:27 PM, Michael wrote:
> It seems like it can return either a class or an instance of a class.
> Like
> super( C, self)
> is like casting self as superclass C.
> However if you omit the second argument entirely you get a class.
Inside a class C: these are all equivalent:
super().method(arg) # python 3
super(C, self).method(arg)
super(C).method(self, arg)
it is similar to how you can call
class C(object):
def method(self, arg):
pass
inst = C()
# these are equivalent
inst.method(arg)
C.method(inst, arg)
python 2.x restricts the first argument of an unbound method to instance
of the class; python 3.x does not have such restriction. Thus, it is
possible in python 3.x to have:
>>> class A(object):
... pass
...
>>> class B(object):
... def anom(self):
... print(self)
...
>>> a = A()
>>> B.anom(a)
<__main__.A object at 0x0165C630>
the same thing in python 2 would be an error.
> The former is considered a "bound" object. I'm really not clear on the
> idea of "binding" in Python.
The first argument of a bound method (the argument self) is
automatically redirected to the instance. Notice when you called a method:
class A(object):
# this declaration have 3 arguments
def foo(self, a, b):
pass
a = A()
# called by only 2 arguments
a.foo(1, 2)
because a.foo binds method A.foo() and `a`; and `a` is passed implicitly
as the first argument to A.foo(a, 1, 2).
More information about the Python-list
mailing list