Python初学之抽象类

抽象类是包含抽象方法的类,而抽象方法不包含任何可实现的代码,只能在其子类中实现抽象函数的代码。

子类继承父类的成员变量和成员函数。

1.定义抽象类

在定义抽象类前需要从类库abc导入ABCmeta类(即Metaclass for defining Abstract BaseClasses,抽象基类的元类)和abstractmethod类。

在定义抽象类时需要在类定义中加入如下代码:

__metaclass__ = ABCmeta,即指定该类的元类是ABCmeta。所谓元类就是创建类的类。

在定义抽象方法时需要在前面加入如下代码:

@abstractmethod

因为抽象方法不包含任何可实现的代码,因此其函数体通常使用pass。下面演示抽象类的实现和多态。所谓的多态指的是在抽象类中定义一个方法,可以在其子类中重新实现,不同子类中实现的方法也不尽相同。


class shape(object):
	__metaclass__= ABCMeta#指定该类的元类是ABCMeta

	def __init__(self):
		self.color = 'black'
	@abstractmethod
	def draw(self):
		pass

	
>>> class circle(shape):
	def __init__(self,x,y,r):
		self.x = x
		self.y = y
		self.r = r
	def draw(self):
		print'draw circle:(%d,%d,%d)'%(self.x,self.y,self.r)

		
>>> class line(shape):
	def __init__(self,x1,y1,x2,y2):
		self.x1 = x1
		self.y1 = y1
		self.x2 = x2
		self.y2 = y2
	def draw(self):
		print'draw circle:(%d,%d,%d,%d)'%(self.x1,self.y1,self.x2,self.y2)

		
>>> c = circle(1,2,3)
>>> c.draw()
draw circle:(1,2,3)
>>> l = line(1,2,3,4)
>>> l.draw()
draw circle:(1,2,3,4)

因为抽象类的子类都实现抽象类中定义的抽象方法,所以可以把同一抽象类各种子类对象定义成一个序列的元素,然后遍历列表,调用抽象方法。


>>> c = circle(1,2,3)
>>> c.draw()
draw circle:(1,2,3)
>>> l = line(1,2,3,4)
>>> l.draw()
draw circle:(1,2,3,4)
>>> c = circle(1,2,3)
>>> l = line(1,2,3,4)
>>> list = []
>>> list.append(c,l)
>>> list.append(c)
>>> list.append(l)
>>> for i in range(len(list)):
	list[i].draw()

	
draw circle:(1,2,3)
draw circle:(1,2,3,4)


在此,复习一下类的复制,(1):新对象名 = 原有对象名。

如上文,cc = c = circle(1,2,3)

cc.draw(),其输出结果与c.draw()一样。

(2):参数传递。

def drawcircle(c):

    if isinstance(c,shape):

    c.draw()

c 1 = circle(1,2,3)

drawcircle(c1)


  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值