Python 最大的坑

文 / 山哥

TAG: global 类变量 实例变量 public private

如果你熟悉不止一门语言,那么Python最大的坑,莫过于变量的作用域了。如果你写的程序反复检查逻辑没有问题,那一般都是变量作用域出现了问题。

1, Global 和 Local
2, 类变量和实例变量

局部变量和全局变量

以下代码会报错local variable ‘xxx’ referenced before assignment

xxx = 23
def PrintFileName(strFileName):
    if xxx == 23:
        print strFileName
        xxx = 24

PrintFileName("file")

如何解决呢?加上global 就可以了。

xxx = 23
def PrintFileName(strFileName):
    global xxx
    if xxx == 23:
        print strFileName
        xxx = 24

PrintFileName("file")

类变量和实例变量

在下例中

  • population是类变量每实例化一个对象,它都会加1。
  • name是实例变量,每个对象私有。
>> class Person:
>>     population = 0
>>     def __init__(self, name: str):
>>         self.name = name
>>         Person.population += 1

>> p1 = Person("p1")
>> p2 = Person("p2")
>> p2.population
Output: 2
>> p2.name
Output: 'p2'
>> p1.name
Output: 'p1'

离题万丈扩展阅读

Python 类的成员变量和方法,默认全是Public的。如果想要设为Private,那么名字请以 双下划线开头。
EG. def __my_method():

    原文作者:山哥Samuel
    原文地址: https://www.jianshu.com/p/a9be5b93fe6a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞