python nonlocal 问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python nonlocal 问题相关的知识,希望对你有一定的参考价值。

class Employee:
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
nonlocal empCount
empCount += 1
def displayCount(self):
print( "Total Employee %d :" + str(Employee.empCount))
def displayEmployee(self):
print( "Name : " + self.name + ", Salary: " + str(self.salary))
emp = Employee("wang",1000)
emp.displayEmployee()
emp.displayCount()

报错。请问是什么问题,谢谢。
File "C:\Users\WangJY\Desktop\Auto Script\class.py", line 10
nonlocal empCount
^
SyntaxError: no binding for nonlocal 'empCount' found

参考技术A displayCount函数里,Employee.empCount调用有问题!由于是自身函数调用自身变量,所以应用self.empCount形式。本回答被提问者和网友采纳 参考技术B fnServerData": function ( sSource, aoData, fnCallback )
/* Add some extra data to the sender */
aoData.push( "name": "more_data", "value": "my_value" );
$.getJSON( sSource, aoData, function (json)
/* Do whatever additional processing you want on the callback, then tell DataTables */
fnCallback(json)
);

以上是关于python nonlocal 问题的主要内容,如果未能解决你的问题,请参考以下文章

python nonlocal 问题

Python 关键字之 nonlocal

Python 2.x 中的 nonlocal 关键字

python引用局部变量之nonlocal

Ruby 等价于 python nonlocal

python nonlocal 的具体原理