类使用类方法,访问 success_list
是可以的!
from loguru import logger
success_list: list[float] = [1,2,3,4,5,6,7,8]
class Myclass:
def run(self):
logger.debug(success_list)
Myclass().run()
logger.debug(success_list)
运行结果:
2022-07-29 16:15:23.838 | DEBUG | __main__:run:8 - [1, 2, 3, 4, 5, 6, 7, 8]
2022-07-29 16:15:23.838 | DEBUG | __main__:<module>:13 - [1, 2, 3, 4, 5, 6, 7, 8]
但是加两行代码就不行了
from loguru import logger
success_list: list[float] = [1,2,3,4,5,6,7,8]
class Myclass:
def run(self):
logger.debug(success_list)
success_list = success_list[1:]
logger.debug(success_list)
Myclass().run()
logger.debug(success_list)
运行结果:
Traceback (most recent call last):
File "/Users/ponponon/Desktop/code/me/ideaboom/tools copy.py", line 12, in <module>
Myclass().run()
File "/Users/ponponon/Desktop/code/me/ideaboom/tools copy.py", line 8, in run
logger.debug(success_list)
UnboundLocalError: local variable 'success_list' referenced before assignment
主注意,报错在logger.debug(success_list)
而不是success_list = success_list[1:]
但是加上 global 又可以了!?
from loguru import logger
success_list: list[float] = [1,2,3,4,5,6,7,8]
class Myclass:
def run(self):
global success_list
logger.debug(success_list)
success_list = success_list[1:]
logger.debug(success_list)
Myclass().run()
logger.debug(success_list)
运行结果:
2022-07-29 16:16:33.181 | DEBUG | __main__:run:9 - [1, 2, 3, 4, 5, 6, 7, 8]
2022-07-29 16:16:33.181 | DEBUG | __main__:run:11 - [2, 3, 4, 5, 6, 7, 8]
2022-07-29 16:16:33.181 | DEBUG | __main__:<module>:15 - [2, 3, 4, 5, 6, 7, 8]
为什么第一份代码可以不加 global ?
当内部作用域想修改外部作用域的变量时,就要用到 global,
如果只是访问的话,可以不用加。