Python 2.7 Python2.7:Self用作位置参数,但不用作关键字参数
下面是一个简单的例子: 这在python 3.5和2.7中都适用:Python 2.7 Python2.7:Self用作位置参数,但不用作关键字参数,python-2.7,self,keyword-argument,Python 2.7,Self,Keyword Argument,下面是一个简单的例子: 这在python 3.5和2.7中都适用: class A(object): def __init__(self, foo): self._foo = foo class B(A): def __init__(self, foo): A.__init__(self, foo=foo) b = B(1) 换行: A.__init__(self, foo=foo) 到 在python 3.5中工作没有问题,但在python 2.7中,您
class A(object):
def __init__(self, foo):
self._foo = foo
class B(A):
def __init__(self, foo):
A.__init__(self, foo=foo)
b = B(1)
换行:
A.__init__(self, foo=foo)
到
在python 3.5中工作没有问题,但在python 2.7中,您将收到以下错误:
Traceback (most recent call last):
File "self_key.py", line 9, in <module>
b = B(1)
File "self_key.py", line 7, in __init__
A.__init__(self=self, foo=foo)
TypeError: unbound method __init__() must be called with A instance as first argument (got nothing instead)
也会是一样的
我的问题是,为什么在调用函数时,我们可以完美地将该参数指定为位置参数(a.。\uuuu init\uuuuo(self,foo=foo)
),但当我们尝试将其作为关键字参数传递时(a.。\uuu init\uuuu(this=self,foo=foo)
),python 2.7会抛出一个错误
始终使用self
作为实例方法的第一个参数
来源:事实上,除非你前后一致,否则你不必使用
self
关键字。看看这个例子,我将self
更改为test
:
class funcs():
def init(test, a, b):
test.a=a
test.b=b
def plus(test):
c = test.a + test.b
print"%d + %d = %d" %(test.a, test.b, c)
def minus(test):
c = test.a - test.b
print"%d - %d = %d" %(test.a, test.b, c)
obj = funcs()
obj.init(10, 6)
obj.plus()
obj.minus()
您可以尝试混合这些实例名称,这样它就不会被命名为self
class A(object):
def __init__(a_obj, foo):
a_obj._foo = foo
class B(A):
def __init__(self, test, foo):
A.__init__(self, a_obj=test, foo=foo) # here you pass object of class B and actually another object of class B
a = A(2)
b = B(a, 1)
给出输出:
A.__init__(self, a_obj=test, foo=foo)
TypeError: __init__() got multiple values for keyword argument 'a_obj'
我不确定通过像这样传递这些对象,您实际上想要实现什么。在您的代码中,A类中的self
和B类中的self
不是相同的对象
我想这里:
A.\uu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。我使用这种方法而不是使用super()
来控制多重继承中父级的\uuu init\uuu
调用顺序,就像这样[.所以A中的self和B中的self应该是同一个对象,因为我将B的引用传递给A的\uuu init\uuuu
方法。这是可以的,因为B继承了A,所以它也是A。
class A(object):
def __init__(a_obj, foo):
a_obj._foo = foo
class B(A):
def __init__(self, test, foo):
A.__init__(self, a_obj=test, foo=foo) # here you pass object of class B and actually another object of class B
a = A(2)
b = B(a, 1)
A.__init__(self, a_obj=test, foo=foo)
TypeError: __init__() got multiple values for keyword argument 'a_obj'