zoukankan      html  css  js  c++  java
  • 对python变量的理解

    #!/usr/bin/python
    
    class Person:
       '''some words content or descriptions!''' name
    ='luomingchuan' _age = 18 __mail = 'gordon.tongji' def __init__(self): self.normal = 'normal' self._single = 'single' self.__double = 'double' def print_self(self): print 'instance variables: ', self.normal,self._single,self.__double print 'class variables: ',self.name,self._age,self.__mail

      python类的理解对于编程蛮重要的,对于我个人来说,我习惯这样编写,双引号的可以用来描述私有变量,单引号的用来描述实例变量,不带引号的用来描述类的变量,这样系统化分后,以上代码就可以书写为

    #!/usr/bin/python
    
    class Person:
    global global_var name
    ='luomingchuan' age = 18 __mail = 'gordon.tongji' def __init__(self): self._normal = 'normal' self._single = 'single' self.__double = 'double' def print_self(self): print 'instance variables: ', self.normal,self._single,self.__double print 'class variables: ',self.name,self._age,self.__mail

       接下来谈谈对三种变量的理解,global是使用全局的一个变量,这个只是在这声明,其实python的global我的理解是类似于全局的静态变量。类的变量是针对与这一类的变量,他们共享的变量,初值只在第一次实例化时候赋予,类似于共享于类之间的全局变量,是这个类所共同拥有的,当然和全局变量还是有区别的话,实例变量是伴随这实例化的这个实例的,访问的时候一定要使用self才能够获得,其定义的时候是在__init__()函数内定义的。私有变量貌似外面不可获得,其实可以通过__classname__doublequotename获得。

    #!/usr/bin/python
    
    class Person:
        name='luomingchuan'
        _age = 18
        __mail = 'gordon.tongji'
        count = 0
        def __init__(self):
            self.normal = 'normal'
            self._single = 'single'
            self.__double = 'double'
            Person.count += 1
          #self.count += 1       #count += 1 will cause error
    def print_self(self): print 'instance variables: ', self.normal,self._single,self.__double print 'class variables: ',self.name,self._age,self.__mail def __del__(self): Person.count -= 1
            #self.count -=1 def countPerson(self): print self.count

    python比较有趣的是,竟然定义在内部的静态变量不能通过在内部直接调用,这能通过self.来访问或者类名加点,

  • 相关阅读:
    【最短路】The 2019 Asia Nanchang First Round Online Programming Contest Fire-Fighting Hero (Dijkstra)
    【积累】The 2019 Asia Nanchang First Round Online Programming Contest The Nth Item (矩阵快速幂 k进制快速幂)
    【线段树】The Preliminary Contest for ICPC Asia Xuzhou 2019 Colorful String(回文树+线段树+状压/bitset)
    allure参数说明及代码示例
    Idea+maven+testng+reportng生成测试报告
    ubuntu 16.04 镜像下载
    new AndroidDriver报错java.lang.NoSuchMethodError: com.google.common.base.Throwables.throwIfUnchecked
    Appium常用的API
    Appium常用的定位方法
    adb 指令总结
  • 原文地址:https://www.cnblogs.com/luomingchuan/p/3671789.html
Copyright © 2011-2022 走看看