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

  • 相关阅读:
    将Nginx添加到windows服务中
    springboot使用redis管理session
    GIT常用命令
    阻止360、谷歌浏览器表单自动填充
    谈谈对Spring IOC的理解
    同一个Nginx服务器同一端口配置多个代理服务
    LeetCode 653. Two Sum IV
    109. Convert Sorted List to Binary Search Tree(根据有序链表构造平衡的二叉查找树)
    108. Convert Sorted Array to Binary Search Tree(从有序数组中构造平衡的BST)
    LeetCode 236. Lowest Common Ancestor of a Binary Tree(二叉树求两点LCA)
  • 原文地址:https://www.cnblogs.com/luomingchuan/p/3671789.html
Copyright © 2011-2022 走看看