python 面向对象
2016-06-21 17:19
513 查看
实例:
定义类时,类名下面的用引号包起来的字符串作为类的说明
注意:
用eclipse工具,类及其方法未定义但已调用的情况下,可通过快捷键 Ctrl + 1 自动创建类及方法
定义类时,类名下面的用引号包起来的字符串作为类的说明
#!/usr/bin/python # -*- coding: UTF-8 -*- #1、创建类 class Employee: "所有员工的基类" empCount = 0 #构造方法 def __init__(self, name, salary): self.name = name self.salary = salary #注意下面类变量使用方法 类名.类变量名 在类内部和外部都这样使用 Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary "析构方法" def __del__(self): class_name = Employee.__name__ print class_name, '销毁' "2、创建 Employee 类的第一个对象" emp1 = Employee("Zara", 2000) "创建 Employee 类的第二个对象" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() #3、属性访问方法 emp1.age = 7 # 添加一个 'age' 属性 emp1.name = "tom" # 修改 'name' 属性 del emp1.age # 删除 'age' 属性 emp1.displayEmployee() emp2.displayEmployee() "类变量" print "Total Employee %d" % Employee.empCount ''' 你也可以使用以下函数的方式来访问属性: getattr(obj, name[, default]) : 访问对象的属性。 hasattr(obj,name) : 检查是否存在一个属性。 setattr(obj,name,value) : 设置一个属性。如果属性不存在,会创建一个新属性。 delattr(obj, name) : 删除属性。 ''' print hasattr(emp1, 'age') # 如果存在 'age' 属性返回 True。 if hasattr(emp1, 'age'): print getattr(emp1, 'age') # 返回 'age' 属性的值 setattr(emp1, 'name', 'ann') # 添加属性 'name' 值为 ann if hasattr(emp1, 'age'): delattr(emp1, 'age') # 删除属性 'age' ''' 4、Python内置类属性 __dict__ : 类的属性(包含一个字典,由类的数据属性组成) __doc__ :类的文档字符串 __name__: 类名 __module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod) __bases__ : 类的所有父类构成元素(包含了以个由所有父类组成的元组) ''' print "Employee.__doc__:", Employee.__doc__ print "Employee.__name__:", Employee.__name__ print "Employee.__module__:", Employee.__module__ print "Employee.__bases__:", Employee.__bases__ print "Employee.__dict__:", Employee.__dict__ print dir()
注意:
用eclipse工具,类及其方法未定义但已调用的情况下,可通过快捷键 Ctrl + 1 自动创建类及方法
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法