类 面向对象技术简介
类:类是抽象的,在使用的时候通常会找到这个类的一个具体的存在,使用这个具体的存在。一个类可以找到多个对象
对象: 某一个具体事物的存在,在现实世界中可以是看的到摸得着的。 可以直接使用
类与对象的关系: 类就是创建对象的模板
类的构成:
1.类的名称:类名
2.类的属性:一组数据
3.类的方法:允许对进行操作的方法(行为)
对象:当创建对象时,就是用一个模子,来制造一个实物
class Door(): # "门的类"
def __init__(self,size,color,type): #"初始化门的数据"
self.size = size
self.color = color
self.type = type
def open(self): # "门打开的方法"
print("这个%s门打开了" %self.type)
def off(self): #"门关闭的方法"
print("这个%s门关闭了" %self.type)
door1 = Door(16,'red','木门') #门的实例化1
door1.open()
door2 = Door(34,'white','铝合金')#门的实例化2
door2.off()
def Door(size,color,type):
"门的函数,此处使用函数的嵌套来实现面向对象设计"
def open(door):
"门打开的动作"
print("这个%s门打开了"%door['type'])
def off(door):
"门关闭的动作"
print("这个%s门关闭了" % door['type'])
def init (size,color,type):
"初始化门的字典--含有门的特征(属性)及门的方法"
door={
"size":size,
"color":color,
"type":type,
"open":open,
"off":off
}
return door
door = init(size,color,type)
return door
door1 =Door(16,'red','木门') #调用门的函数
print(door1 )
ss=door1 ['open']
print(ss)
door1['open'](door1) #运行门的打开方法
door2 =Door(34,'white','铝合金') #调用门的函数
door2['off'](door2) #运行门的打开方法
class test:
data = 1
def __init__(self):
self.property=0
def test2(self):
print 'hello'
if __name__=='__main__':
t = test()
print test.data
print t.data
print test.test2
print t.test2()
print test.test2(t)
(1)封装:对外部隐藏对象的工作细节
(2)继承:子类自动共享父类之间数据和方法的机制
(3)多态:可以对不同类的对象调用相同的方法,产生不同的结果
类封装
class MyClass:
"""一个简单的类实例"""
i = 12345
def f(self): #self代表类的实例,而非类
return 'hello world'
#实例化类
x = MyClass()
#访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())
类的方法
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。
#类定义
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#实例化类
p = people('runoob',10,30)
p.speak()
继承
Python 同样支持类的继承,如果一种语言不支持继承,类就没有什么意义。派生类的定义如下所示:
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
s = student('ken',10,60,3)
s.speak()
多继承 #类定义
Python同样有限的支持多继承形式。多继承的类定义形如下例:
class people: #类定义
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
class student(people): #单继承示例
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类的方法
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
class speaker(): #另一个类,多重继承之前的准备
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s"%(self.name,self.topic))
class sample(speaker,student): #多重继承
a =''
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
test = sample("Tim",25,80,4,"Python")
test.speak() #方法名同,默认调用的是在括号中排前地父类的方法
方法重写
如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,实例如下:
实例(Python 3.0+)
class Parent: # 定义父类
def myMethod(self):
print ('调用父类方法')
class Child(Parent): # 定义子类
def myMethod(self):
print ('调用子类方法')
c = Child() # 子类实例
c.myMethod() # 子类调用重写方法
super(Child,c).myMethod() #用子类对象调用父类已被覆盖的方法
类属性与方法
类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
类的方法
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例。
self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定是用 self。
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods。
实例
类的私有属性实例如下:
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) # 报错,实例不能访问私有变量
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)
类的专有方法:
init : 构造函数,在生成对象时调用
del : 析构函数,释放对象时使用
repr : 打印,转换
setitem : 按照索引赋值
getitem: 按照索引获取值
len: 获得长度
cmp: 比较运算
call: 函数调用
add: 加运算
sub: 减运算
mul: 乘运算
truediv: 除运算
mod: 求余运算
pow: 乘方
class Person():
#人口数和土地面积属于人类共享的信息,设置为类公有变量
population = 0
earth = 10000
#诺亚方舟能载多少人,自然不应该让每个人都知道,设置为类私有变量
__noahCapacity =10
def __init__(self, name, age, salary):
self.name = name #年龄也类似,设置为对象的公有变量
self.__salary = salary
def __privateFun(self):
print "这是私有成员函数的输出" #在类的内部访问对象的公有和私有变量
def printInstance(self):
print "*"*50,"公有成员函数被调用","*"*50
print "在类内部可以通过self访问对象的公有和私有变量:"
print "name: %s age: %d salary:%d" % (self.name, self.age, self.__salary)
print "通过类内部的成员函数,在类的内部调用私有成员函数:"
self.__privateFun()
print "*"*120 #在类的内部访问类的公有变量和私有变量
def printClass(self):
print "-"*50,"公有成员函数被调用","-"*50
print "在类内部可以通过self访问类的公有和私有变量:"
print "population: %d earth: %d NoahCapacity: %d" % (self.population, self.earth, self.__noahCapacity)
print "在类内部也可以通过类名访问类的公有和私有变量:"
print "population: %d earth: %d NoahCapacity: %d" % (Person.population, Person.earth, Person.__noahCapacity)
print "-"*120
if __name__ == "__main__":
tom = Person("Tom", 24, 9000)
print "在类外部访问属性操作","|"*100
print "在类外部可以通过对象名访问类的公有变量:"
print "population: %d earth: %d" % (tom.population, tom.earth)
print "在类外部也可以通过对象名用特殊方法访问类的私有变量(仅用于调试):"
print "NoahCapacity: %d" % tom._Person__noahCapacity print "在类外部可以通过对象名访问对象的公有变量:"
print "name: %s age: %d" % (tom.name, tom.age)
print "在类外部也可以通过类名访问类的公有变量:"
print "population: %d earth: %d" % (Person.population, Person.earth)
print "|"*120
print ""
print "在类的外部调用类的成员函数","|"*100
print "在类外通过对象名调用类的公有成员函数" tom.printInstance() tom.printClass()
print "|"*120
```