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

  • 相关阅读:
    node的安装与配置
    linux下查看是否安装某个软件
    怎么把apk文件部署在云服务器上
    github怎么搜索!!!
    node.js搭建本地服务器的两种方式(anywhere和http-server)
    js中迭代方法
    yarn和npm的区别
    总结一下测试工程师学习的博客和网站
    我的周记1——”云想衣裳花想容"
    2019/11/22 再聊职业规划——5年后,你想成为怎样的人?
  • 原文地址:https://www.cnblogs.com/luomingchuan/p/3671789.html
Copyright © 2011-2022 走看看