您的位置:首页 > 编程语言 > Python开发

python 面向对象

2016-06-21 17:19 513 查看
实例:

定义类时,类名下面的用引号包起来的字符串作为类的说明

#!/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 面向对象