Skip to main content
 首页 » 编程设计

Python将其中一个参数代入self

2025年05月04日14lvdongjie

我在 Python 中遇到了一个我无法解决的有趣情况。我有一个功能 一个类中的定义 def a(self, x, y): 并且它是从其他地方调用的,比如 a(par1, par2)。然而,发生的事情是 par1 被替换而不是 self,par2 而不是 x 和 y 未初始化。但事实并非如此:应该分别放置 par1 和 par2 而不是 x 和 y Python 应该自己得到 self。这在 Python 2.7 中工作正常,但是这个有趣的事情发生在 3.2 中。方法 a 没有任何修饰符,但是我调用它的方法有 @classmethod 修饰符。有点奇怪,可能第三个版本改了@classmethod。如果有人知道发生了什么或如何使事情正常工作,请告诉。

谢谢!

请您参考如下方法:

根据您的描述,我猜测代码与此类似:

class Test(object): 
 
    def a(self, par1, par2='empty'): 
        print(self, par1, par2) 
 
    @classmethod 
    def b(cls, fjord): 
        print(fjord) 
        cls.a('par1', 'par2') 
 
test = Test() 
test.a('this', 'that') 
test.b('cold') 

在 2.7 中,它会像这样崩溃:

(<__main__.Test object at 0x00B4A710>, 'this', 'that') 
 
cold 
 
Traceback (most recent call last): 
  File "test.py", line 11, in <module> 
    test.b('cold') 
  File "test.py", line 7, in b 
    cls.a('par1', 'par2') 
TypeError: unbound method a() must be called with Test instance as first argument 
           (got str instance instead) 

虽然在 3.2 中它工作得很好——因为未绑定(bind)的方法不再存在,它们只是函数。

self 不是实例的原因恰恰是因为它是从类方法中调用的:类方法没有获取 self 所以它不能传递它。