class的好处就是内部结构井井有条,代码没有不裸露,都封装到属性或方法里
这是一个函数里带子函数的例子:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
The output of the example code is:
After local assignment: test spam After nonlocal assignment: nonlocal spam After global assignment: nonlocal spam In global scope: global spam
https://docs.python.org/3.7/tutorial/classes.html#scopes-and-namespaces-example
这样的嵌套定义还是第一次看到,但是从外部无法调用scope_test()内部的函数do_local()、do_nonlocal()、do_global()。
而如果写成类,就可以轻易的调用类的方法,而且类内部除了定义的各种方法和属性,没有零散的语句了,如果想增加类的功能,可以新增方法,而不需要在原有的代码上做修改(那是最头痛的)。
而且因为可以加很多方法,所以每个方法都不必写的很复杂,这样即使修改某个方法的内部代码,也不会太复杂。