2016-02-09 41 views
0

python中绑定的方法和绑定方法究竟是什么?对象创建时它有什么不同?什么是python中的绑定和非绑定方法

我是新手到Python我写了这一小段代码

class newclass: 
     def function1(self,var2): 
     self.var2=var2 
     print var2 
     self.fun_var=var2 

    newobject = newclass 
    newobject.function1(64) 

我喜欢这个

Traceback (most recent call last): 
    File "basic_class.py", line 8, in <module> 
    newobject.function1(64) 
TypeError: unbound method function1() must be called with newclass instance as first argument (got int instance instead) 

究竟是什么绑定的方法和不受约束的方法在Python得到错误

回答

2

Python中正确的对象初始化为:

newobject = newclass() # Note the parens 

绑定方法是一种实例方法,即。它适用于object。未绑定的方法是一个简单的函数,可以在没有对象上下文的情况下调用。详细讨论见this answer

请注意,在Python 3中,未绑定的方法概念被删除。

1

在你的情况下,你应该先创建newclass的实例,然后调用function1。

class newclass: 
    def function1(self,var2): 
    self.var2=var2 
    print var2 
    self.fun_var=var2 

newobject = newclass 
newobject().function1(64)