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.来访问或者类名加点,

  • 相关阅读:
    网站微信扫码登陆总结以及在小程序登陆两者关联和关系,vue以及uniapp
    微信扫码登陆在chrome浏览器失败,浏览器禁止重定向
    element-ui多个表单如何同时验证
    vscode中react代码提示插件
    echarts主题全局颜色定义、自定义折线颜色--彩色折线图echarts
    vue本地储存加密
    Echarts多条折线图 y轴数值与实际值不符解决方法
    vue中swiper@5.3.6使用,
    解决 swiper设置loop为true时,echarts图表不显示
    vue+nginx配置,以及nginx配置跨域
  • 原文地址:https://www.cnblogs.com/luomingchuan/p/3671789.html
Copyright © 2011-2022 走看看