python学习笔记(三)面向对象
2017-05-20 15:25
423 查看
创建类
使用class语句来创建一个新类,class之后为类的名称并以冒号结尾,如下实例:class ClassName: '类的帮助信息' #类文档字符串 class_suite #类体
类的帮助信息可以通过ClassName.doc查看。
class_suite 由类成员,方法,数据属性组成。
#!/usr/bin/python # -*- coding: UTF-8 -*- 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 #"创建 Employee 类的第一个对象" emp1 = Employee("Zara", 2000) #"创建 Employee 类的第二个对象" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
输出:
Name : Zara , Salary: 2000 Name : Manni , Salary: 5000 Total Employee 2
内置类属性和类属性的操作方法
Python内置类属性:__dict__ : 类的属性(包含一个字典,由类的数据属性组成) __doc__ :类的文档字符串 __name__: 类名 __module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod) __bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
访问属性:
getattr(obj, name[, default]) : 访问对象的属性。
hasattr(obj,name) : 检查是否存在一个属性。
setattr(obj,name,value) : 设置一个属性。如果属性不存在,会创建一个新属性。
delattr(obj, name) : 删除属性
#!/usr/bin/python # -*- coding: UTF-8 -*- 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 #"创建 Employee 类的第一个对象" emp1 = Employee("Zara", 2000) #"创建 Employee 类的第二个对象" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
emp1.age = 7 # 添加一个 'age' 属性
print "emp1.age : ", emp1.age
emp1.age = 8 # 修改 'age' 属性
print "emp1.age : ", emp1.age
#del emp1.age # 删除 'age' 属性
print "hasattr : ", hasattr(emp1, 'age') # 如果存在 'age' 属性返回 True
print "setattr : ", setattr(emp1, 'age', 9) # 添加属性 'age' 值为 9
print "getattr : ", getattr(emp1, 'age') # 返回 'age' 属性的值
#delattr(empl, 'age') # 删除属性 'age'
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__
输出:
Name : Zara , Salary: 2000 Name : Manni , Salary: 5000 Total Employee 2
emp1.age : 7
emp1.age : 8
hasattr : True
setattr : None
getattr : 9
Employee.__doc__: 所有员工的基类
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount': <function displayCount at 0x7f00032247d0>, 'empCount': 2, 'displayEmployee': <function displayEmployee at 0x7f0003224848>, '__doc__': '\xe6\x89\x80\xe6\x9c\x89\xe5\x91\x98\xe5\xb7\xa5\xe7\x9a\x84\xe5\x9f\xba\xe7\xb1\xbb', '__init__': <function __init__ at 0x7f0003224758>}
类的继承
面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。继承完全可以理解成类之间的类型和子类型关系。在python中继承中的一些特点:
1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。 2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数 3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。
语法:
派生类的声明,与他们的父类类似,继承的基类列表跟在类名之后,如下所示:
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
#!/usr/bin/python # -*- coding: UTF-8 -*- class Parent: # 定义父类 parentAttr = 100 def __init__(self): print "调用父类构造函数" def parentMethod(self): print '调用父类方法' def setAttr(self, attr): print '调用父类方法setAttr' Parent.parentAttr = attr def getAttr(self): print "父类属性 :", Parent.parentAttr class Child(Parent): # 定义子类 def __init__(self): print "调用子类构造方法" def childMethod(self): print '调用子类方法 child method' c = Child() # 实例化子类 c.childMethod() # 调用子类的方法 c.parentMethod() # 调用父类方法 c.setAttr(200) # 再次调用父类的方法 c.getAttr() # 再次调用父类的方法
输出:
调用子类构造方法 调用子类方法 child method 调用父类方法 调用父类方法setAttr 父类属性 : 200
issubclass和isinstance
issubclass() - 布尔函数判断一个类是另一个类的子类或者子孙类,语法:issubclass(sub,sup) isinstance(obj, Class) 布尔函数如果obj是Class类的实例对象或者是一个Class子类的实例对象则返回true。
print "isinstance(c,Child):",isinstance(c,Child); print "isinstance(c,Parent):",isinstance(c,Parent); print "issubclass(Child,Parent):",issubclass(Child,Parent);
输出:
isinstance(c,Child): True isinstance(c,Parent): True issubclass(Child,Parent): True
方法重写
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Parent: # 定义父类
parentAttr = 100
def __init__(self):
print "调用父类构造函数"
def parentMethod(self):
print '调用父类方法'
def setAttr(self, attr):
print '调用父类方法setAttr'
Parent.parentAttr = attr
def getAttr(self):
print "父类属性 :", Parent.parentAttr
def myMethod(self):
print '调用父类方法myMethod'
class Child(Parent): # 定义子类
def __init__(self):
print "调用子类构造方法"
def childMethod(self):
print '调用子类方法 child method'
def myMethod(self):
print '调用子类方法myMethod'
c = Child() # 实例化子类
c.childMethod() # 调用子类的方法
c.parentMethod() # 调用父类方法
c.setAttr(200) # 再次调用父类的方法
c.getAttr() # 再次调用父类的方法
print "isinstance(c,Child):",isinstance(c,Child); print "isinstance(c,Parent):",isinstance(c,Parent); print "issubclass(Child,Parent):",issubclass(Child,Parent);
c.myMethod()
输出:
调用子类构造方法 调用子类方法 child method 调用父类方法 调用父类方法setAttr 父类属性 : 200
isinstance(c,Child): True isinstance(c,Parent): True issubclass(Child,Parent): True
调用子类方法myMethod
运算符重载
#!/usr/bin/python class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1 + v2
输出:
Vector (7, 8)
类属性与方法
类的私有属性__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
类的方法
在类地内部,使用def关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数self,且为第一个参数
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,不能在类地外部调用。在类的内部调用 self.__private_methods
#!/usr/bin/python # -*- coding: UTF-8 -*- class JustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 def count(self): self.__secretCount += 1 self.publicCount += 1 print self.__secretCount counter = JustCounter() counter.count() counter.count() print counter.publicCount #print counter.__secretCount # 报错,实例不能访问私有变量
输出:
1 2 2
Python不允许实例化的类访问私有数据,但你可以使用 object._className__attrName 访问属性,将如下代码替换以上代码的最后一行代码:
print counter._JustCounter__secretCount
单下划线、双下划线、头尾双下划线说明:
__foo__: 定义的是特列方法,类似 __init__() 之类的。 _foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import * __foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
1.python学习网站
http://www.runoob.com/python/python-tutorial.html
相关文章推荐
- Python学习笔记-面向对象篇
- python学习笔记-Day06-Day07(面向对象)
- python学习笔记3:面向对象的高级特性3 定制类
- Python学习笔记(三)函数、面向对象、模块发布
- Python 学习笔记 - 面向对象(其他)
- python学习笔记-(8)初识python面向对象
- Python 学习笔记(二):时间,函数,异常,面向对象
- Python 学习笔记 - 面向对象(特殊成员)
- Python 学习笔记 - 面向对象(类成员)
- Python学习笔记-初级(五):面向对象
- 【Python】学习笔记八:面向对象
- Python面向对象的编程--Python学习笔记五
- python学习笔记(面向对象)
- python学习笔记1:面向对象的高级特性1__slots__
- 【极客学院】-python学习笔记-Python快速入门(面向对象-引入外部文件-Web2Py创建网站)
- Python3学习笔记04-循环、函数、面向对象
- Python 2.7 学习笔记 面向对象的编程
- Python学习笔记十一:面向对象
- Python学习笔记(三)——模块|面向对象
- Python 学习笔记 - 面向对象(封装,继承和多态)