![](/img/trans.png)
[英]Why is the class passed to a function being called inside a class function when using self in Python?
[英]Function inside class not being called
我有一个python类和几个函数,第一次调用第二次。 但是,2nd永远不会被调用。 _method2()
调用之后的行也不会执行。
class call_methods():
def _method1(self, context):
print "Now call method 2";
this._method2(context);
print "Finish";
return {}
def _method2(self, context={}):
print "method 2 called"
return {}
输出:
Now call method 2
仅出现第一个打印语句。
问题类似于“ 功能未调用”,但建议的解决方案似乎不适用于此功能。
this._method2(context); ===> self._method2(context)
this
不python.You存在必须使用self
。还有;
不需要,而是遵循适当的缩进。将第二个函数修改为
def _method2(self, context={}):
您有未定义的名称this
,因此Python会抱怨。 您可以更改第二个method
_method2()
来接受参数self
,这在Python中是一种约定,表示已创建并要引用的类的instance
:
class call_methods:
def _method1(self, context):
print "Now call Method 2"
self._method2(context)
print "finish"
return {}
def _method2(self, context={}):
print "Method 2 Called"
return {}
如果要使用已创建的类的实例通过_method1
调用_method2
,则必须再次在引用该实例的_methdo2()
的调用中提供self
参数,这是通过在函数的self
参数上调用函数来隐式完成的_method1
。
更改后的输出为:
In [27]: cls1 = call_methods()
In [28]: cls1._method1("con")
Now call Method 2
Method 2 Called
finish
Out[28]: {}
PS:声明类时不需要括号()
,没有区别。 您可能想看看Python 2中的New Style Classs
它应该是:
class call_methods():
def _method1(self,context):
print "Now call method 2";
this._method2(context);
print "Finish";
return {}
def _method2(self, context={}):
print "method 2 called"
return {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.