对python变量的理解
2014-04-17 20:08
274 查看
#!/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.来访问或者类名加点,
相关文章推荐
- Python快速学习07:文本文件的操作
- python encode和decode的妙用
- Python快速学习07:文本文件的操作
- virtualenv创建独立的Python环境
- 杂: PYTHON上数据储存:推荐h5py
- 序列化Python对象
- python: 编码格式non-assii
- python元祖和文件用法举例
- Python 列表和字典用法解释
- python多线程
- 【转】新手该如何学python怎么学好python?
- python webservice gzip压缩与解压缩
- 一段关于python 闭包的例子
- ubuntu 安装 python MySQLdb 支持
- 加载调用这个函数的包下的所有模块 python函数
- Project Euler 31~35
- [转]Python 之 使用 PIL 库做图像处理
- (转)python requests 高级用法 -- 包括SSL 证书错误的解决方案
- python IDLE的使用
- python mssql insert 插入datetime类型