定义一个类
类的格式:
class 类名(父类):
类的内容
#类名后面有括号的类,称为新式类
#括号里面的内容是父类的名称;程序中,所有类的父类都是object
class Animals(object):
pass
print Animals
执行结果:
类的数据属性
# coding:utf-8
class Animals(object):
#类的数据属性
name = 'Tom'
age = 8
#访问类的数据属性
print Animals.name
print Animals.age
执行结果:
类的方法
# coding:utf-8
class Animals(object):
name = "Tom"
age = 8
weight = 10
#类的方法=函数
#在类中定义的函数叫做方法
#类的方法中,python解释器要求第一个形参必须是self;与java中的this类似
# self实质上是类实例化后的对象本身
def eat(self):
print "eating......"
#类的实例化产生的就是对象; 把抽象的类创造出实际存在的事物
#p1就是实例化产生的对象
p1 = Animals()
#调用类的属性
print p1.name
# 调用类的方法
p1.eat()
执行结果:
面对对象的三大特征:封装、继承、多态
封装:
封装实际上是把数据封装到某个地方,以后再去调用被封装在某处的内容或者数据:
封装数据
调用封装数据
通过对象直接调用
通过self间接调用
# coding:utf-8
class Animals(object):
# __init__ 构造方法,确切的说应该是初始化;
# 当类实例化时会自动调用__init__构造方法;
# name, age, weight在这里是必选参数,当实例化时必须要传参,否则报错;
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
# eat方法
def eat(self):
print "%s eating......" %(self.name)
self.weight += 2
# drink方法
def drink(self):
print "%s is drinking....." %(self.name)
self.weight += 1
# 对象可以实例化多个;
Tom = Animals("Tom", 8, 10) #实例化实际执行了2个操作:实例化和初始化。实例化是将Animals类具象化为对象Tom,初始化指的是执行类里面的__init__构造方法(初始化方法)
Jack = Animals("Jack", 5, 3)
# 在Animals内部,self实质上就是类的实例化对象Tom和Jack
print '名字:%s 年龄:%d 体重:%d' %(Tom.name,Tom.age,Tom.weight)
Tom.eat()
print '目前体重:%d' %(Tom.weight)
Tom.drink()
print '目前体重:%d' %(Tom.weight)
执行结果:
练习1:
创建一个类(People),拥有的方法为砍柴、娶媳妇、回家。实例化对象,执行相应的方法
# coding:utf-8
class People(object):
def __init__(self,name):
self.name = name
#砍柴
def cut(self):
return "%s砍柴" %(self.name)
#娶媳妇
def marry(self):
return "%s娶媳妇" %(self.name)
#回家
def home(self):
return "%s回家" %(self.name)
p1 = People('p1')
p2 = People('p2')
p3 = People('p3')
print p1.cut()
print p2.marry()
print p3.home()
执行结果:
练习2:栈的数据结构
#栈遵循先进后出,后进先出的原则
栈的方法:
入栈(push),出栈(pop),栈顶元素(top),栈的长度(lenght),显示栈元素(view),判断栈是否为空(isempty)
操作结果:
栈类的实例化,入栈2次,出栈1次,显示最终栈元素
# coding:utf-8
class Stack(object):
def __init__(self):
self.table = []
def push(self,value):
print '%s 入栈' %value
self.table.append(value)
def pop(self):
if not self.isempty():
print '%s 出栈' %self.table[-1]
self.table.pop()
def top(self):
if not self.isempty():
print '栈顶元素:%s' %self.table[-1]
def lenght(self):
print '栈的长度;%d' %len(self.table)
def view(self):
print '显示栈元素:',
for i in self.table:
print i,
print
def isempty(self): #self.table为[]则返回True,否则返回False
return self.table == []
s1 = Stack()
s1.push(1)
s1.push(2)
s1.pop()
s1.view()
执行结果:
练习3:队列的数据结构
#队列遵循先进先出,后进后出原则
队列的方法:
入队(enqueue),出队(dequeue), 队头元素(head), 队尾元素(tail),队列的长度(lenght), 显示队列元素(view),判断队列是否为空(isempty)
操作结果:
队列类的实例化,入队5次,出队1次,显示最终队列元素
# coding:utf-8
class Queue(object):
def __init__(self):
self.table = []
def enqueue(self,value):
print '%s 入队' %value
self.table.append(value)
def dequeue(self):
if not self.isempty():
print '%s 出队' %self.table[0]
self.table.pop(0)
def head(self):
if not self.isempty():
print '队头元素:%s' %self.table[0]
def tail(self):
if not self.isempty():
print '队尾元素:%s' %self.table[-1]
def lenght(self):
print '队列的长度;%d' %len(self.table)
def view(self):
print '显示队列元素:',
for i in self.table:
print i,
print
def isempty(self): #self.table为[]则返回True,否则返回False
return self.table == []
s1 = Queue()
s1.enqueue(1)
s1.enqueue(2)
s1.enqueue(3)
s1.enqueue(4)
s1.enqueue(5)
s1.dequeue()
s1.view()
执行结果:
继承:
父类(基类)和子类(派生类)
注意:类的属性名和方法名不能相同,因为相同的话,实例化时会优先调用方法,导致属性无法调用
# coding:utf-8
# Animals是父类/基类;
class Animals(object):
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def eat(self):
print "%s is eating...,体重+2" % (self.name)
self.weight += 2
def drink(self):
print "%s is drinking..." % (self.name)
self.weight += 1
def get_weight(self):
print '%s is %d kg' %(self.name,self.weight)
# Dog是Animal的子类/派生类;
class Dog(Animals):
# 类里面的方法第一个参数必须是self
def call(self):
print "%s:汪、汪、汪..." % (self.name)
# Cat是Animal的子类/派生类;
class Cat(Animals):
def call(self):
print "%s:喵、喵、喵..." % (self.name)
Tom = Cat("Tom",12,10)
Tom.eat()
Tom.get_weight()
Tom.call()
执行结果:
重写父类的构造函数:
父类名.__init__(self,形参)super(自己类的名称, self).__init__(形参)
#不需要明确告诉父类的名称
#如果父类改变,只需修改class语句后面的继承关系即可
# coding:utf-8
# Animals是父类/基类;
class Animals(object):
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def eat(self):
print "%s eating......" % (self.name)
self.weight += 2
# Dog是Animal的子类/派生类;
class Dog(Animals):
# name, age, weight, dogid
def __init__(self, name, age, weight, dogid):
# 重写父类构造函数;
self.name = name
self.age = age
self.weight = weight
self.dogid = dogid
# Cat是Animal的子类/派生类;
class Cat(Animals):
# name, age, weight, food
def __init__(self, name, age, weight, food):
self.name = name
self.age = age
self.weight = weight
self.food = food
Spike = Dog("Spike", 3, 10, '001')
print Spike.name
print Spike.dogid
Tom = Cat("Tom", 2, 5, "fish")
print Tom.food
执行结果:
多态:
当父类和子类有相同的方法时, 调用优先执行子类的方法
# coding:utf-8
# Animals是父类/基类;
class Animals(object):
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def eat(self):
print "%s eating......" % (self.name)
self.weight += 2
class Cat(Animals):
def eat(self):
print "%s eating......" % (self.name)
self.weight += 1
class Dog(Animals):
def eat(self):
print "%s eating......" % (self.name)
self.weight += 3
Spike = Dog("Spike", 12, 12)
Spike.eat()
print Spike.weight
执行结果:可以看到执行完eat方法之后weight增加了3,说明调用的是子类的eat方法
特殊的类属性:
# coding:utf-8
class Base(object):
pass
class Animals(object):
'''
父类Animals:
Attritube:
'''
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def eat(self):
print "%s eating......" % (self.name)
self.weight += 2
class Cat(Animals):
def eat(self):
print "%s eating......" % (self.name)
self.weight += 1
class Dog(Animals, Base):
def eat(self):
print "%s eating......" % (self.name)
self.weight += 3
print Animals.__name__ #打印类名称
print Animals.__doc__ #打印类的说明,__doc__属性不能继承给子类
print Animals.__bases__ #打印类的所有父类,以元组类型返回
print Dog.__bases__ #打印类的所有父类,以元组类型返回
print Animals.__dict__ #以字典的方式返回类的方法和属性
print Animals.__module__ #如果类不是被导入的, 显示为__main__,如果类是被import导入的, 则显示类所在的模块名
执行结果: